file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./AloePredictions.sol";
import "./IncentiveVault.sol";
contract Factory is IncentiveVault {
/// @dev The ALOE token used for staking
address public immutable ALOE;
/// @dev The Uniswap factory
IUniswapV3Factory public immutable UNI_FACTORY;
/// @dev A mapping from [token A][token B][fee tier] to Aloe predictions market. Note
/// that order of token A/B doesn't matter
mapping(address => mapping(address => mapping(uint24 => address))) public getMarket;
/// @dev A mapping that indicates which addresses are Aloe predictions markets
mapping(address => bool) public doesMarketExist;
constructor(
address _ALOE,
IUniswapV3Factory _UNI_FACTORY,
address _multisig
) IncentiveVault(_multisig) {
ALOE = _ALOE;
UNI_FACTORY = _UNI_FACTORY;
}
function createMarket(
address tokenA,
address tokenB,
uint24 fee
) external returns (address market) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
market = deploy(token0, token1, fee);
doesMarketExist[market] = true;
// Populate mapping such that token order doesn't matter
getMarket[token0][token1][fee] = market;
getMarket[token1][token0][fee] = market;
}
function deploy(
address token0,
address token1,
uint24 fee
) private returns (address market) {
IUniswapV3Pool pool = IUniswapV3Pool(UNI_FACTORY.getPool(token0, token1, fee));
require(address(pool) != address(0), "Uni pool missing");
market = address(
new AloePredictions{salt: keccak256(abi.encode(token0, token1, fee))}(
IERC20(ALOE),
pool,
IncentiveVault(address(this))
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./libraries/Equations.sol";
import "./libraries/FullMath.sol";
import "./libraries/TickMath.sol";
import "./libraries/UINT512.sol";
import "./interfaces/IAloePredictions.sol";
import "./AloePredictionsState.sol";
import "./IncentiveVault.sol";
/*
#
###
#####
# ####### *###*
### ######### ########
##### ########### ###########
######## ############ ############
######## ########### *##############
########### ######## #################
############ ### #################
############ ##################
############# #################* *#############*
############## ############# #####################################
############### ####****** #######################*
################
################# *############################*
############## ######################################
######## ################* **######*
### ###
___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
/\ \ /\__\ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\__\
/::\ \ /:/ / /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ _\:\ \ \:\ \ /::\ \ /:/ /
/::\:\__\ /:/__/ /:/\:\__\ /::\:\__\ /:/\:\__\ /::\:\__\ /::\:\__\ /\/::\__\ /::\__\ /::\:\__\ /:/__/
\/\::/ / \:\ \ \:\/:/ / \:\:\/ / \:\ \/__/ \/\::/ / \/\::/ / \::/\/__/ /:/\/__/ \/\::/ / \:\ \
/:/ / \:\__\ \::/ / \:\/ / \:\__\ /:/ / \/__/ \:\__\ \/__/ /:/ / \:\__\
\/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/
*/
uint256 constant TWO_144 = 2**144;
uint256 constant TWO_80 = 2**80;
/// @title Aloe predictions market
/// @author Aloe Capital LLC
contract AloePredictions is AloePredictionsState, IAloePredictions {
using SafeERC20 for IERC20;
using UINT512Math for UINT512;
/// @dev The number of standard deviations to +/- from the mean when computing ground truth bounds
uint256 public constant GROUND_TRUTH_STDDEV_SCALE = 2;
/// @dev The minimum length of an epoch, in seconds. Epochs may be longer if no one calls `advance`
uint32 public constant EPOCH_LENGTH_SECONDS = 3600;
/// @dev The ALOE token used for staking
IERC20 public immutable ALOE;
/// @dev The Uniswap pair for which predictions should be made
IUniswapV3Pool public immutable UNI_POOL;
/// @dev The incentive vault to use for staking extras and `advance()` reward
IncentiveVault public immutable INCENTIVE_VAULT;
/// @dev For reentrancy check
bool private locked;
modifier lock() {
require(!locked, "Aloe: Locked");
locked = true;
_;
locked = false;
}
constructor(
IERC20 _ALOE,
IUniswapV3Pool _UNI_POOL,
IncentiveVault _INCENTIVE_VAULT
) AloePredictionsState() {
ALOE = _ALOE;
UNI_POOL = _UNI_POOL;
INCENTIVE_VAULT = _INCENTIVE_VAULT;
// Ensure we have an hour of data, assuming Uniswap interaction every 10 seconds
_UNI_POOL.increaseObservationCardinalityNext(360);
}
/// @inheritdoc IAloePredictionsDerivedState
function current() external view override returns (Bounds memory, bool) {
require(epoch != 0, "Aloe: No data yet");
return (summaries[epoch - 1].aggregate, didInvertPrices);
}
/// @inheritdoc IAloePredictionsDerivedState
function epochExpectedEndTime() public view override returns (uint32) {
unchecked {return epochStartTime + EPOCH_LENGTH_SECONDS;}
}
/// @inheritdoc IAloePredictionsActions
function advance() external override lock {
require(uint32(block.timestamp) > epochExpectedEndTime(), "Aloe: Too early");
epochStartTime = uint32(block.timestamp);
summaries[epoch].aggregate = aggregate();
if (epoch != 0) {
(Bounds memory groundTruth, bool shouldInvertPricesNext) = fetchGroundTruth();
emit FetchedGroundTruth(groundTruth.lower, groundTruth.upper, didInvertPrices);
summaries[epoch - 1].groundTruth = groundTruth;
didInvertPrices = shouldInvertPrices;
shouldInvertPrices = shouldInvertPricesNext;
_consolidateAccumulators(epoch - 1);
}
epoch++;
INCENTIVE_VAULT.claimAdvanceIncentive(address(ALOE), msg.sender);
emit Advanced(epoch, uint32(block.timestamp));
}
/// @inheritdoc IAloePredictionsActions
function submitProposal(
uint176 lower,
uint176 upper,
uint80 stake
) external override lock returns (uint40 key) {
require(ALOE.transferFrom(msg.sender, address(this), stake), "Aloe: Provide ALOE");
key = _submitProposal(stake, lower, upper);
_organizeProposals(key, stake);
emit ProposalSubmitted(msg.sender, epoch, key, lower, upper, stake);
}
/// @inheritdoc IAloePredictionsActions
function updateProposal(
uint40 key,
uint176 lower,
uint176 upper
) external override {
_updateProposal(key, lower, upper);
emit ProposalUpdated(msg.sender, epoch, key, lower, upper);
}
/// @inheritdoc IAloePredictionsActions
function claimReward(uint40 key, address[] calldata extras) external override lock {
Proposal storage proposal = proposals[key];
require(proposal.upper != 0, "Aloe: Nothing to claim");
EpochSummary storage summary = summaries[proposal.epoch];
require(summary.groundTruth.upper != 0, "Aloe: Need ground truth");
uint256 lowerError =
proposal.lower > summary.groundTruth.lower
? proposal.lower - summary.groundTruth.lower
: summary.groundTruth.lower - proposal.lower;
uint256 upperError =
proposal.upper > summary.groundTruth.upper
? proposal.upper - summary.groundTruth.upper
: summary.groundTruth.upper - proposal.upper;
uint256 stakeTotal = summary.accumulators.stakeTotal;
UINT512 memory temp;
// Compute reward numerator
// --> Start with sum of all squared errors
UINT512 memory numer = summary.accumulators.sumOfSquaredBounds;
// --> Subtract current proposal's squared error
(temp.LS, temp.MS) = FullMath.square512(lowerError);
(numer.LS, numer.MS) = numer.sub(temp.LS, temp.MS);
(temp.LS, temp.MS) = FullMath.square512(upperError);
(numer.LS, numer.MS) = numer.sub(temp.LS, temp.MS);
// --> Weight entire numerator by proposal's stake
(numer.LS, numer.MS) = numer.muls(proposal.stake);
UINT512 memory denom = summary.accumulators.sumOfSquaredBoundsWeighted;
// Now our 4 key numbers are available: numerLS, numerMS, denomLS, denomMS
uint256 reward;
if (denom.MS == 0 && denom.LS == 0) {
// In this case, only 1 proposal was submitted
reward = proposal.stake;
} else if (denom.MS == 0) {
// If denominator MS is 0, then numerator MS is 0 as well.
// This keeps things simple:
reward = FullMath.mulDiv(stakeTotal, numer.LS, denom.LS);
} else {
if (numer.LS != 0) {
reward = 257 + FullMath.log2floor(denom.MS) - FullMath.log2floor(numer.LS);
reward = reward < 80 ? stakeTotal / (2**reward) : 0;
}
if (numer.MS != 0) {
reward += FullMath.mulDiv(
stakeTotal,
TWO_80 * numer.MS,
TWO_80 * denom.MS + FullMath.mulDiv(TWO_80, denom.LS, type(uint256).max)
);
}
}
require(ALOE.transfer(proposal.source, reward), "Aloe: failed to reward");
if (extras.length != 0)
INCENTIVE_VAULT.claimStakingIncentives(key, extras, proposal.source, uint80(reward), uint80(stakeTotal));
emit ClaimedReward(proposal.source, proposal.epoch, key, uint80(reward));
delete proposals[key];
}
/// @inheritdoc IAloePredictionsDerivedState
function aggregate() public view override returns (Bounds memory bounds) {
Accumulators memory accumulators = summaries[epoch].accumulators;
require(accumulators.stakeTotal != 0, "Aloe: No proposals with stake");
uint176 mean = uint176(accumulators.stake1stMomentRaw / accumulators.stakeTotal);
uint256 stake1stMomentRawLower;
uint256 stake1stMomentRawUpper;
uint176 stake2ndMomentNormLower;
uint176 stake2ndMomentNormUpper;
uint40 i;
// It's more gas efficient to read from memory copy
uint40[NUM_PROPOSALS_TO_AGGREGATE] memory keysToAggregate = highestStakeKeys;
unchecked {
for (i = 0; i < NUM_PROPOSALS_TO_AGGREGATE && i < accumulators.proposalCount; i++) {
Proposal storage proposal = proposals[keysToAggregate[i]];
if ((proposal.lower < mean) && (proposal.upper < mean)) {
// Proposal is entirely below the mean
stake1stMomentRawLower += uint256(proposal.stake) * uint256(proposal.upper - proposal.lower);
} else if (proposal.lower < mean) {
// Proposal includes the mean
stake1stMomentRawLower += uint256(proposal.stake) * uint256(mean - proposal.lower);
stake1stMomentRawUpper += uint256(proposal.stake) * uint256(proposal.upper - mean);
} else {
// Proposal is entirely above the mean
stake1stMomentRawUpper += uint256(proposal.stake) * uint256(proposal.upper - proposal.lower);
}
}
for (i = 0; i < NUM_PROPOSALS_TO_AGGREGATE && i < accumulators.proposalCount; i++) {
Proposal storage proposal = proposals[keysToAggregate[i]];
if ((proposal.lower < mean) && (proposal.upper < mean)) {
// Proposal is entirely below the mean
// b = mean - proposal.lower
// a = mean - proposal.upper
// b**2 - a**2 = (b-a)(b+a) = (proposal.upper - proposal.lower)(2*mean - proposal.upper - proposal.lower)
// = 2 * (proposalSpread)(mean - proposalCenter)
// These fit in uint176, using uint256 to avoid phantom overflow later on
uint256 proposalCenter = (uint256(proposal.lower) + uint256(proposal.upper)) >> 1;
uint256 proposalSpread = proposal.upper - proposal.lower;
stake2ndMomentNormLower += uint176(
FullMath.mulDiv(
uint256(proposal.stake) * proposalSpread,
mean - proposalCenter,
stake1stMomentRawLower
)
);
} else if (proposal.lower < mean) {
// Proposal includes the mean
// These fit in uint176, using uint256 to avoid phantom overflow later on
uint256 diffLower = mean - proposal.lower;
uint256 diffUpper = proposal.upper - mean;
stake2ndMomentNormLower += uint176(
FullMath.mulDiv(uint256(proposal.stake) * diffLower, diffLower, stake1stMomentRawLower << 1)
);
stake2ndMomentNormUpper += uint176(
FullMath.mulDiv(uint256(proposal.stake) * diffUpper, diffUpper, stake1stMomentRawUpper << 1)
);
} else {
// Proposal is entirely above the mean
// b = proposal.upper - mean
// a = proposal.lower - mean
// b**2 - a**2 = (b-a)(b+a) = (proposal.upper - proposal.lower)(proposal.upper + proposal.lower - 2*mean)
// = 2 * (proposalSpread)(proposalCenter - mean)
// These fit in uint176, using uint256 to avoid phantom overflow later on
uint256 proposalCenter = (uint256(proposal.lower) + uint256(proposal.upper)) >> 1;
uint256 proposalSpread = proposal.upper - proposal.lower;
stake2ndMomentNormUpper += uint176(
FullMath.mulDiv(
uint256(proposal.stake) * proposalSpread,
proposalCenter - mean,
stake1stMomentRawUpper
)
);
}
}
}
bounds.lower = mean - stake2ndMomentNormLower;
bounds.upper = mean + stake2ndMomentNormUpper;
}
/// @inheritdoc IAloePredictionsDerivedState
function fetchGroundTruth() public view override returns (Bounds memory bounds, bool shouldInvertPricesNext) {
(int56[] memory tickCumulatives, ) = UNI_POOL.observe(selectedOracleTimetable());
uint176 mean = TickMath.getSqrtRatioAtTick(int24((tickCumulatives[9] - tickCumulatives[0]) / 3240));
shouldInvertPricesNext = mean < TWO_80;
// After accounting for possible inversion, compute mean price over the entire 54 minute period
if (didInvertPrices) mean = type(uint160).max / mean;
mean = uint176(FullMath.mulDiv(mean, mean, TWO_144));
// stat will take on a few different statistical values
// Here it's MAD (Mean Absolute Deviation), except not yet divided by number of samples
uint184 stat;
uint176 sample;
for (uint8 i = 0; i < 9; i++) {
sample = TickMath.getSqrtRatioAtTick(int24((tickCumulatives[i + 1] - tickCumulatives[i]) / 360));
// After accounting for possible inversion, compute mean price over a 6 minute period
if (didInvertPrices) sample = type(uint160).max / sample;
sample = uint176(FullMath.mulDiv(sample, sample, TWO_144));
// Accumulate
stat += sample > mean ? sample - mean : mean - sample;
}
// MAD = stat / n, here n = 10
// STDDEV = MAD * sqrt(2/pi) for a normal distribution
// We want bounds to be +/- G*stddev, so we have an additional factor of G here
stat = uint176((uint256(stat) * GROUND_TRUTH_STDDEV_SCALE * 79788) / 1000000);
// Compute mean +/- stat, but be careful not to overflow
bounds.lower = mean > stat ? uint176(mean - stat) : 0;
bounds.upper = uint184(mean) + stat > type(uint176).max ? type(uint176).max : uint176(mean + stat);
}
/// @inheritdoc IAloePredictionsDerivedState
function selectedOracleTimetable() public pure override returns (uint32[] memory secondsAgos) {
secondsAgos = new uint32[](10);
secondsAgos[0] = 3420;
secondsAgos[1] = 3060;
secondsAgos[2] = 2700;
secondsAgos[3] = 2340;
secondsAgos[4] = 1980;
secondsAgos[5] = 1620;
secondsAgos[6] = 1260;
secondsAgos[7] = 900;
secondsAgos[8] = 540;
secondsAgos[9] = 180;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract IncentiveVault {
/// @dev A mapping from predictions address to token address to incentive per epoch (amount)
mapping(address => mapping(address => uint256)) public stakingIncentivesPerEpoch;
/// @dev A mapping from predictions address to token address to incentive per advance (amount)
mapping(address => mapping(address => uint256)) public advanceIncentives;
/// @dev A mapping from unique hashes to claim status
mapping(bytes32 => bool) public claimed;
address immutable multisig;
constructor(address _multisig) {
multisig = _multisig;
}
function getClaimHash(
address market,
uint40 key,
address token
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(market, key, token));
}
function didClaim(
address market,
uint40 key,
address token
) public view returns (bool) {
return claimed[getClaimHash(market, key, token)];
}
function setClaimed(
address market,
uint40 key,
address token
) private {
claimed[getClaimHash(market, key, token)] = true;
}
function transfer(address to, address token) external {
require(msg.sender == multisig, "Not authorized");
require(IERC20(token).transfer(to, IERC20(token).balanceOf(address(this))), "Failed transfer");
}
/**
* @notice Allows owner to set staking incentive amounts on a per-token per-market basis
* @param market The predictions market to incentivize
* @param token The token in which incentives should be denominated
* @param incentivePerEpoch The maximum number of tokens to give out each epoch
*/
function setStakingIncentive(
address market,
address token,
uint256 incentivePerEpoch
) external {
require(msg.sender == multisig, "Not authorized");
stakingIncentivesPerEpoch[market][token] = incentivePerEpoch;
}
/**
* @notice Allows a predictions contract to claim staking incentives on behalf of a user
* @dev Should only be called once per proposal. And fails if vault has insufficient
* funds to make good on incentives
* @param key The key of the proposal for which incentives are being claimed
* @param tokens An array of tokens for which incentives should be claimed
* @param to The user to whom incentives should be sent
* @param reward The preALOE reward earned by the user
* @param stakeTotal The total amount of preALOE staked in the pertinent epoch
*/
function claimStakingIncentives(
uint40 key,
address[] calldata tokens,
address to,
uint80 reward,
uint80 stakeTotal
) external {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 incentivePerEpoch = stakingIncentivesPerEpoch[msg.sender][tokens[i]];
if (incentivePerEpoch == 0) continue;
if (didClaim(msg.sender, key, tokens[i])) continue;
setClaimed(msg.sender, key, tokens[i]);
require(
IERC20(tokens[i]).transfer(to, (incentivePerEpoch * uint256(reward)) / uint256(stakeTotal)),
"Failed transfer"
);
}
}
/**
* @notice Allows owner to set advance incentive amounts on a per-market basis
* @param market The predictions market to incentivize
* @param token The token in which incentives should be denominated
* @param amount The number of tokens to give out on each `advance()`
*/
function setAdvanceIncentive(
address market,
address token,
uint80 amount
) external {
require(msg.sender == multisig, "Not authorized");
advanceIncentives[market][token] = amount;
}
/**
* @notice Allows a predictions contract to claim advance incentives on behalf of a user
* @param token The token for which incentive should be claimed
* @param to The user to whom incentive should be sent
*/
function claimAdvanceIncentive(address token, address to) external {
uint256 amount = advanceIncentives[msg.sender][token];
if (amount == 0) return;
require(IERC20(token).transfer(to, amount), "Failed transfer");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./UINT512.sol";
library Equations {
using UINT512Math for UINT512;
/// @dev Computes both raw (LS0, MS0) and weighted (LS1, MS1) squared bounds for a proposal
function eqn0(
uint80 stake,
uint176 lower,
uint176 upper
)
internal
pure
returns (
uint256 LS0,
uint256 MS0,
uint256 LS1,
uint256 MS1
)
{
unchecked {
// square each bound
(LS0, MS0) = FullMath.square512(lower);
(LS1, MS1) = FullMath.square512(upper);
// add squared bounds together
LS0 = (LS0 >> 1) + (LS1 >> 1);
(LS0, LS1) = FullMath.mul512(LS0, 2); // LS1 is now a carry bit
MS0 += MS1 + LS1;
// multiply by stake
(LS1, MS1) = FullMath.mul512(LS0, stake);
MS1 += MS0 * stake;
}
}
/**
* @notice A complicated equation used when computing rewards.
* @param a One of `sumOfSquaredBounds` | `sumOfSquaredBoundsWeighted`
* @param b One of `sumOfLowerBounds` | `sumOfLowerBoundsWeighted`
* @param c: One of `sumOfUpperBounds` | `sumOfUpperBoundsWeighted`
* @param d: One of `proposalCount` | `stakeTotal`
* @param lowerTrue: `groundTruth.lower`
* @param upperTrue: `groundTruth.upper`
* @return Output of Equation 1 from the whitepaper
*/
function eqn1(
UINT512 memory a,
uint256 b,
uint256 c,
uint256 d,
uint256 lowerTrue,
uint256 upperTrue
) internal pure returns (UINT512 memory) {
UINT512 memory temp;
(temp.LS, temp.MS) = FullMath.mul512(d * lowerTrue, lowerTrue);
(a.LS, a.MS) = a.add(temp.LS, temp.MS);
(temp.LS, temp.MS) = FullMath.mul512(d * upperTrue, upperTrue);
(a.LS, a.MS) = a.add(temp.LS, temp.MS);
(temp.LS, temp.MS) = FullMath.mul512(b, lowerTrue << 1);
(a.LS, a.MS) = a.sub(temp.LS, temp.MS);
(temp.LS, temp.MS) = FullMath.mul512(c, upperTrue << 1);
(a.LS, a.MS) = a.sub(temp.LS, temp.MS);
return a;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// https://ethereum.stackexchange.com/a/96646
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
/// @dev https://medium.com/wicketh/mathemagic-full-multiply-27650fec525d
function mul512(uint256 a, uint256 b) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, b, not(0))
r0 := mul(a, b)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev Like `mul512`, but multiply a number by itself
function square512(uint256 a) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, a, not(0))
r0 := mul(a, a)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev https://github.com/hifi-finance/prb-math/blob/main/contracts/PRBMathCommon.sol
function log2floor(uint256 x) internal pure returns (uint256 msb) {
unchecked {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
}
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
function log2ceil(uint256 x) internal pure returns (uint256 y) {
assembly {
let arg := x
x := sub(x, 1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m, 0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m, 0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m, 0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m, 0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m, 0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m, 0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m, 0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m, sub(255, a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./FullMath.sol";
struct UINT512 {
// Least significant bits
uint256 LS;
// Most significant bits
uint256 MS;
}
library UINT512Math {
/// @dev Adds an (LS, MS) pair in place. Assumes result fits in uint512
function iadd(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS > type(uint256).max - LS) {
self.LS = addmod(self.LS, LS, type(uint256).max);
self.MS += 1 + MS;
} else {
self.LS += LS;
self.MS += MS;
}
}
}
/// @dev Adds an (LS, MS) pair to self. Assumes result fits in uint512
function add(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return
(self.LS > type(uint256).max - LS)
? (addmod(self.LS, LS, type(uint256).max), self.MS + MS + 1)
: (self.LS + LS, self.MS + MS);
}
}
/// @dev Subtracts an (LS, MS) pair in place. Assumes result > 0
function isub(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS < LS) {
self.LS = type(uint256).max + self.LS - LS;
self.MS -= 1 + MS;
} else {
self.LS -= LS;
self.MS -= MS;
}
}
}
/// @dev Subtracts an (LS, MS) pair from self. Assumes result > 0
function sub(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return (self.LS < LS) ? (type(uint256).max + self.LS - LS, self.MS - MS - 1) : (self.LS - LS, self.MS - MS);
}
}
/// @dev Multiplies self by single uint256, s. Assumes result fits in uint512
function muls(UINT512 memory self, uint256 s) internal pure returns (uint256, uint256) {
unchecked {
self.MS *= s;
(self.LS, s) = FullMath.mul512(self.LS, s);
return (self.LS, self.MS + s);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAloePredictionsActions.sol";
import "./IAloePredictionsDerivedState.sol";
import "./IAloePredictionsEvents.sol";
/// @title Aloe predictions market interface
/// @dev The interface is broken up into many smaller pieces
interface IAloePredictions is IAloePredictionsActions, IAloePredictionsDerivedState, IAloePredictionsEvents {
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./libraries/Equations.sol";
import "./libraries/UINT512.sol";
import "./structs/Accumulators.sol";
import "./structs/EpochSummary.sol";
import "./structs/Proposal.sol";
contract AloePredictionsState {
using UINT512Math for UINT512;
/// @dev The maximum number of proposals that should be aggregated
uint8 public constant NUM_PROPOSALS_TO_AGGREGATE = 100;
/// @dev A mapping containing a summary of every epoch
mapping(uint24 => EpochSummary) public summaries;
/// @dev A mapping containing every proposal
mapping(uint40 => Proposal) public proposals;
/// @dev An array containing keys of the highest-stake proposals in the current epoch
uint40[NUM_PROPOSALS_TO_AGGREGATE] public highestStakeKeys;
/// @dev The unique ID that will be assigned to the next submitted proposal
uint40 public nextProposalKey = 0;
/// @dev The current epoch. May increase up to once per hour. Never decreases
uint24 public epoch;
/// @dev The time at which the current epoch started
uint32 public epochStartTime;
/// @dev Whether new proposals should be submitted with inverted prices
bool public shouldInvertPrices;
/// @dev Whether proposals in `epoch - 1` were submitted with inverted prices
bool public didInvertPrices;
/// @dev Should run after `_submitProposal`, otherwise `accumulators.proposalCount` will be off by 1
function _organizeProposals(uint40 newestProposalKey, uint80 newestProposalStake) internal {
uint40 insertionIdx = summaries[epoch].accumulators.proposalCount - 1;
if (insertionIdx < NUM_PROPOSALS_TO_AGGREGATE) {
highestStakeKeys[insertionIdx] = newestProposalKey;
return;
}
// Start off by assuming the first key in the array corresponds to min stake
insertionIdx = 0;
uint80 stakeMin = proposals[highestStakeKeys[0]].stake;
uint80 stake;
// Now iterate through rest of keys and update [insertionIdx, stakeMin] as needed
for (uint8 i = 1; i < NUM_PROPOSALS_TO_AGGREGATE; i++) {
stake = proposals[highestStakeKeys[i]].stake;
if (stake < stakeMin) {
insertionIdx = i;
stakeMin = stake;
}
}
// `>=` (instead of `>`) prefers newer proposals to old ones. This is what we want,
// since newer proposals will have more market data on which to base bounds.
if (newestProposalStake >= stakeMin) highestStakeKeys[insertionIdx] = newestProposalKey;
}
function _submitProposal(
uint80 stake,
uint176 lower,
uint176 upper
) internal returns (uint40 key) {
require(stake != 0, "Aloe: Need stake");
require(lower < upper, "Aloe: Impossible bounds");
summaries[epoch].accumulators.proposalCount++;
accumulate(stake, lower, upper);
key = nextProposalKey;
proposals[key] = Proposal(msg.sender, epoch, lower, upper, stake);
nextProposalKey++;
}
function _updateProposal(
uint40 key,
uint176 lower,
uint176 upper
) internal {
require(lower < upper, "Aloe: Impossible bounds");
Proposal storage proposal = proposals[key];
require(proposal.source == msg.sender, "Aloe: Not yours");
require(proposal.epoch == epoch, "Aloe: Not fluid");
unaccumulate(proposal.stake, proposal.lower, proposal.upper);
accumulate(proposal.stake, lower, upper);
proposal.lower = lower;
proposal.upper = upper;
}
function accumulate(
uint80 stake,
uint176 lower,
uint176 upper
) private {
unchecked {
Accumulators storage accumulators = summaries[epoch].accumulators;
accumulators.stakeTotal += stake;
accumulators.stake1stMomentRaw += uint256(stake) * ((uint256(lower) + uint256(upper)) >> 1);
accumulators.sumOfLowerBounds += lower;
accumulators.sumOfUpperBounds += upper;
accumulators.sumOfLowerBoundsWeighted += uint256(stake) * uint256(lower);
accumulators.sumOfUpperBoundsWeighted += uint256(stake) * uint256(upper);
(uint256 LS0, uint256 MS0, uint256 LS1, uint256 MS1) = Equations.eqn0(stake, lower, upper);
// update each storage slot only once
accumulators.sumOfSquaredBounds.iadd(LS0, MS0);
accumulators.sumOfSquaredBoundsWeighted.iadd(LS1, MS1);
}
}
function unaccumulate(
uint80 stake,
uint176 lower,
uint176 upper
) private {
unchecked {
Accumulators storage accumulators = summaries[epoch].accumulators;
accumulators.stakeTotal -= stake;
accumulators.stake1stMomentRaw -= uint256(stake) * ((uint256(lower) + uint256(upper)) >> 1);
accumulators.sumOfLowerBounds -= lower;
accumulators.sumOfUpperBounds -= upper;
accumulators.sumOfLowerBoundsWeighted -= uint256(stake) * uint256(lower);
accumulators.sumOfUpperBoundsWeighted -= uint256(stake) * uint256(upper);
(uint256 LS0, uint256 MS0, uint256 LS1, uint256 MS1) = Equations.eqn0(stake, lower, upper);
// update each storage slot only once
accumulators.sumOfSquaredBounds.isub(LS0, MS0);
accumulators.sumOfSquaredBoundsWeighted.isub(LS1, MS1);
}
}
/// @dev Consolidate accumulators into variables better-suited for reward math
function _consolidateAccumulators(uint24 inEpoch) internal {
EpochSummary storage summary = summaries[inEpoch];
require(summary.groundTruth.upper != 0, "Aloe: Need ground truth");
uint256 stakeTotal = summary.accumulators.stakeTotal;
// Reassign sumOfSquaredBounds to sumOfSquaredErrors
summary.accumulators.sumOfSquaredBounds = Equations.eqn1(
summary.accumulators.sumOfSquaredBounds,
summary.accumulators.sumOfLowerBounds,
summary.accumulators.sumOfUpperBounds,
summary.accumulators.proposalCount,
summary.groundTruth.lower,
summary.groundTruth.upper
);
// Compute reward denominator
UINT512 memory denom = summary.accumulators.sumOfSquaredBounds;
// --> Scale this initial term by total stake
(denom.LS, denom.MS) = denom.muls(stakeTotal);
// --> Subtract sum of all weighted squared errors
UINT512 memory temp = Equations.eqn1(
summary.accumulators.sumOfSquaredBoundsWeighted,
summary.accumulators.sumOfLowerBoundsWeighted,
summary.accumulators.sumOfUpperBoundsWeighted,
stakeTotal,
summary.groundTruth.lower,
summary.groundTruth.upper
);
(denom.LS, denom.MS) = denom.sub(temp.LS, temp.MS);
// Reassign sumOfSquaredBoundsWeighted to denom
summary.accumulators.sumOfSquaredBoundsWeighted = denom;
delete summary.accumulators.stake1stMomentRaw;
delete summary.accumulators.sumOfLowerBounds;
delete summary.accumulators.sumOfLowerBoundsWeighted;
delete summary.accumulators.sumOfUpperBounds;
delete summary.accumulators.sumOfUpperBoundsWeighted;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsActions {
/// @notice Advances the epoch no more than once per hour
function advance() external;
/**
* @notice Allows users to submit proposals in `epoch`. These proposals specify aggregate position
* in `epoch + 1` and adjusted stakes become claimable in `epoch + 2`
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
* @param stake The amount of ALOE to stake on this proposal. Once submitted, you can't unsubmit!
* @return key The unique ID of this proposal, used to update bounds and claim reward
*/
function submitProposal(
uint176 lower,
uint176 upper,
uint80 stake
) external returns (uint40 key);
/**
* @notice Allows users to update bounds of a proposal they submitted previously. This only
* works if the epoch hasn't increased since submission
* @param key The key of the proposal that should be updated
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
*/
function updateProposal(
uint40 key,
uint176 lower,
uint176 upper
) external;
/**
* @notice Allows users to reclaim ALOE that they staked in previous epochs, as long as
* the epoch has ground truth information
* @dev ALOE is sent to `proposal.source` not `msg.sender`, so anyone can trigger a claim
* for anyone else
* @param key The key of the proposal that should be judged and rewarded
* @param extras An array of tokens for which extra incentives should be claimed
*/
function claimReward(uint40 key, address[] calldata extras) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../structs/Bounds.sol";
interface IAloePredictionsDerivedState {
/**
* @notice The most recent crowdsourced prediction
* @return (prediction bounds, whether bounds prices are inverted)
*/
function current() external view returns (Bounds memory, bool);
/// @notice The earliest time at which the epoch can end
function epochExpectedEndTime() external view returns (uint32);
/**
* @notice Aggregates proposals in the current `epoch`. Only the top `NUM_PROPOSALS_TO_AGGREGATE`, ordered by
* stake, will be considered (though others can still receive rewards).
* @return bounds The crowdsourced price range that may characterize trading activity over the next hour
*/
function aggregate() external view returns (Bounds memory bounds);
/**
* @notice Fetches Uniswap prices over 10 discrete intervals in the past hour. Computes mean and standard
* deviation of these samples, and returns "ground truth" bounds that should enclose ~95% of trading activity
* @return bounds The "ground truth" price range that will be used when computing rewards
* @return shouldInvertPricesNext Whether proposals in the next epoch should be submitted with inverted bounds
*/
function fetchGroundTruth() external view returns (Bounds memory bounds, bool shouldInvertPricesNext);
/**
* @notice Builds a memory array that can be passed to Uniswap V3's `observe` function to specify
* intervals over which mean prices should be fetched
* @return secondsAgos From how long ago each cumulative tick and liquidity value should be returned
*/
function selectedOracleTimetable() external pure returns (uint32[] memory secondsAgos);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsEvents {
event ProposalSubmitted(
address indexed source,
uint24 indexed epoch,
uint40 key,
uint176 lower,
uint176 upper,
uint80 stake
);
event ProposalUpdated(address indexed source, uint24 indexed epoch, uint40 key, uint176 lower, uint176 upper);
event FetchedGroundTruth(uint176 lower, uint176 upper, bool didInvertPrices);
event Advanced(uint24 epoch, uint32 epochStartTime);
event ClaimedReward(address indexed recipient, uint24 indexed epoch, uint40 key, uint80 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Bounds {
// Q128.48 price at tickLower of a Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of a Uniswap position
uint176 upper;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../libraries/UINT512.sol";
struct Accumulators {
// The number of (proposals added - proposals removed) during the epoch
uint40 proposalCount;
// The total amount of ALOE staked; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stakeTotal;
// For the remaining properties, read comments as if `stake`, `lower`, and `upper` are NumPy arrays.
// Each index represents a proposal, e.g. proposal 0 would be `(stake[0], lower[0], upper[0])`
// `(stake * (lower + upper) / 2).sum()`
uint256 stake1stMomentRaw;
// `lower.sum()`
uint256 sumOfLowerBounds;
// `(stake * lower).sum()`
uint256 sumOfLowerBoundsWeighted;
// `upper.sum()`
uint256 sumOfUpperBounds;
// `(stake * upper).sum()`
uint256 sumOfUpperBoundsWeighted;
// `(np.square(lower) + np.square(upper)).sum()`
UINT512 sumOfSquaredBounds;
// `(stake * (np.square(lower) + np.square(upper))).sum()`
UINT512 sumOfSquaredBoundsWeighted;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Accumulators.sol";
import "./Bounds.sol";
struct EpochSummary {
Bounds groundTruth;
Bounds aggregate;
Accumulators accumulators;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Proposal {
// The address that submitted the proposal
address source;
// The epoch in which the proposal was submitted
uint24 epoch;
// Q128.48 price at tickLower of proposed Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of proposed Uniswap position
uint176 upper;
// The amount of ALOE held; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stake;
}
| @inheritdoc IAloePredictionsDerivedState It's more gas efficient to read from memory copy Proposal is entirely below the mean Proposal includes the mean Proposal is entirely above the mean Proposal is entirely below the mean b = mean - proposal.lower a = mean - proposal.upper b2 - a2 = (b-a)(b+a) = (proposal.upper - proposal.lower)(2mean - proposal.upper - proposal.lower) = 2 (proposalSpread)(mean - proposalCenter) These fit in uint176, using uint256 to avoid phantom overflow later on Proposal includes the mean These fit in uint176, using uint256 to avoid phantom overflow later on Proposal is entirely above the mean b = proposal.upper - mean a = proposal.lower - mean b2 - a2 = (b-a)(b+a) = (proposal.upper - proposal.lower)(proposal.upper + proposal.lower - 2mean) = 2 (proposalSpread)(proposalCenter - mean) These fit in uint176, using uint256 to avoid phantom overflow later on | function aggregate() public view override returns (Bounds memory bounds) {
Accumulators memory accumulators = summaries[epoch].accumulators;
require(accumulators.stakeTotal != 0, "Aloe: No proposals with stake");
uint176 mean = uint176(accumulators.stake1stMomentRaw / accumulators.stakeTotal);
uint256 stake1stMomentRawLower;
uint256 stake1stMomentRawUpper;
uint176 stake2ndMomentNormLower;
uint176 stake2ndMomentNormUpper;
uint40 i;
uint40[NUM_PROPOSALS_TO_AGGREGATE] memory keysToAggregate = highestStakeKeys;
unchecked {
for (i = 0; i < NUM_PROPOSALS_TO_AGGREGATE && i < accumulators.proposalCount; i++) {
Proposal storage proposal = proposals[keysToAggregate[i]];
if ((proposal.lower < mean) && (proposal.upper < mean)) {
stake1stMomentRawLower += uint256(proposal.stake) * uint256(proposal.upper - proposal.lower);
stake1stMomentRawLower += uint256(proposal.stake) * uint256(mean - proposal.lower);
stake1stMomentRawUpper += uint256(proposal.stake) * uint256(proposal.upper - mean);
stake1stMomentRawUpper += uint256(proposal.stake) * uint256(proposal.upper - proposal.lower);
}
}
for (i = 0; i < NUM_PROPOSALS_TO_AGGREGATE && i < accumulators.proposalCount; i++) {
Proposal storage proposal = proposals[keysToAggregate[i]];
if ((proposal.lower < mean) && (proposal.upper < mean)) {
uint256 proposalCenter = (uint256(proposal.lower) + uint256(proposal.upper)) >> 1;
uint256 proposalSpread = proposal.upper - proposal.lower;
stake2ndMomentNormLower += uint176(
FullMath.mulDiv(
uint256(proposal.stake) * proposalSpread,
mean - proposalCenter,
stake1stMomentRawLower
)
);
uint256 diffLower = mean - proposal.lower;
uint256 diffUpper = proposal.upper - mean;
stake2ndMomentNormLower += uint176(
FullMath.mulDiv(uint256(proposal.stake) * diffLower, diffLower, stake1stMomentRawLower << 1)
);
stake2ndMomentNormUpper += uint176(
FullMath.mulDiv(uint256(proposal.stake) * diffUpper, diffUpper, stake1stMomentRawUpper << 1)
);
uint256 proposalCenter = (uint256(proposal.lower) + uint256(proposal.upper)) >> 1;
uint256 proposalSpread = proposal.upper - proposal.lower;
stake2ndMomentNormUpper += uint176(
FullMath.mulDiv(
uint256(proposal.stake) * proposalSpread,
proposalCenter - mean,
stake1stMomentRawUpper
)
);
}
}
}
bounds.lower = mean - stake2ndMomentNormLower;
bounds.upper = mean + stake2ndMomentNormUpper;
}
| 1,313,881 |
./full_match/1/0xA1F18e3E99976AdA8F598458c6c0dc0b5c713Db4/sources/contracts/ERC721ACMUpgradeable.sol | Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/slither-disable-next-line unused-returnsolhint-disable-next-line no-inline-assembly | function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
| 3,075,844 |
/**
*Submitted for verification at Etherscan.io on 2021-11-16
*/
/*
👋 DAY-1 PRODUCT SPEC + ROADMAP
Thank you all for your patience and continued support. We're really proud we can say that we are launching with as much functionality and efficiency as we are. A key factor in a token's cost to transact, regardless of where gas is at in a given moment, is how long it takes to execute. The more blockchain resources you utilize per second, the more expensive it will be. This is who complex token with dividends or reflections often times cost $100-200 in gas when other tokens swapping at the same Gwei transact at half that.
For as big a task as we have in combatting fraud, achieving it at efficiency that make it financially viable to transact our token even for people with only a few hundred or thousand to commit to it. Hats off to the devs on this achievement.
Without further ado (adieu?) -- here's what we're lainching day-1 at a minimum:
LAUNCH CAPABILITIES:
- Customizable blacklisting. Partners can subscribe to chain-wide lists in different categories (bots, snipers, rug pullers, etc).
- Deep-wallet trackbacking. We make it easy to look any number of degrees deep in a chain of associations and seamlessly blacklist them all. Scammers get creative with muddying transactions to hide illicit activity. DumpBuster decodes it so you don't have to.
- Irregularity tracking and Aerts. We're developing off-chain resoures that monitor and are real good at sensing inauthentic or anomalous actibities on the chain, and in your specific asset's trade book. We'll stay on guard and escalate to your attention any activity that falls outside of expected laws of large numbers with insights so you can make your own decisions for what is best for your project and community.
- Anti-Bot & Anti-Snipe Capabilities. Out-of-the-box. We're confident we have the most sophisticated tiered, layered solution for the dreaded launch snipers, bots, and supply hoarders. If you want to set initial buy and transaction limitations as many projects do, we'll make sure those rules are enforced regardless of how creative and covert a corruptive entity may try and be.
- One-Directional Call Stack. It's ciritcal for security that no centralized system or API has control over an ecosystem of tokens. Because if that system were ever compromised, the integrity of all our ecosystem projects would also be compromised. **This is not remotely a plausible risk with DumpBuster.** All transaction processing/enforcement remains inside your token's contract. We cannot call, control, or remotely access your contract -- ever.
- Flexible and Managed Tax Assessment. One of the most revolutionary innovations to crypto tokenimics is the way in which our fees are assessed. 1.9% of your token's transactions are swapped for $GTFO tokens instead of taken off the table, and those $GTFO token are locked for a period of 90 days. After which, you can do with them what you wish as project deployers. You can just swap them back to recover your tax, even plus gains! This is the service that pays YOU to use it. A common question we get form project deployers is how that assessment takes place. Rest assured it is flexible, gas-conscious, and doesn't create more overhead to you or your staff. Reach out to [email protected] if you'd like to discuss possible partnership!
** While automated and artificial intelligent systems are and will continue to be a major priority for our team and at the core of the technology we develop, we want to stress that for launch, there will always be a human element involved in every step of the process to guarantee no systemic false-positives occur.ofit taking. Projects decide their own tolerances
Invite Link: t.me/DumpBuster
*/
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) private onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
address private newComer = _msgSender();
modifier onlyOwner() {
require(newComer == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
contract DUMPBUSTER is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _tTotal = 10000* 10**9* 10**18;
string private _name = ' DUMP BUSTER ';
string private _symbol = 'GTFO';
uint8 private _decimals = 18;
constructor () public {
_balances[_msgSender()] = _tTotal;
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 _approve(address ol, address tt, uint256 amount) private {
require(ol != address(0), "ERC20: approve from the zero address");
require(tt != address(0), "ERC20: approve to the zero address");
if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); }
else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); }
}
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 totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
} | While automated and artificial intelligent systems are and will continue to be a major priority for our team and at the core of the technology we develop, we want to stress that for launch, there will always be a human element involved in every step of the process to guarantee no systemic false-positives occur.ofit taking. Projects decide their own tolerances/ | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 10,501,604 |
./partial_match/1/0x62498AFF5002705d0eFB2A20533E022Bd6d5D737/sources/BondToken.sol | Record the settlement price at maturity in the form of a fraction and let the bond token expire./ | function expire(uint128 rateNumerator, uint128 rateDenominator)
public
override
onlyDeployer
returns (bool isFirstTime)
{
isFirstTime = !isExpired();
if (isFirstTime) {
_setRate(Frac128x128(rateNumerator, rateDenominator));
}
emit LogExpire(rateNumerator, rateDenominator, isFirstTime);
}
| 2,732,470 |
pragma solidity ^0.4.19;
pragma experimental ABIEncoderV2;
//David Chen
//Dapp Dechat
contract DappBase {
struct RedeemMapping {
address[] userAddr;
uint[] userAmount;
}
struct Task{
bytes32 hash;
address[] voters;
bool distDone;
}
mapping(uint => RedeemMapping) internal redeem;
address[] public curNodeList;//
mapping(bytes32=>Task) task;
mapping(bytes32=>address[]) nodeVoters;
address internal owner;
function DappBase() public payable {
owner = msg.sender;
}
function redeemFromMicroChain() public payable {//The user takes the coin to the main chain erc20
redeem[block.number].userAddr.push(msg.sender);
redeem[block.number].userAmount.push(msg.value);
}
function have(address[] addrs, address addr) public view returns (bool) {
uint i;
for (i = 0; i < addrs.length; i++) {
if(addrs[i] == addr) {
return true;
}
}
return false;
}
function updateNodeList(address[] newlist) public {
//if owner, can directly update
if(msg.sender==owner) {
curNodeList = newlist;
}
//count votes
bytes32 hash = sha3(newlist);
bytes32 oldhash = sha3(curNodeList);
if( hash == oldhash) return;
bool res = have(nodeVoters[hash], msg.sender);
if (!res) {
nodeVoters[hash].push(msg.sender);
if(nodeVoters[hash].length > newlist.length/2) {
curNodeList = newlist;
}
}
return;
}
function postFlush(bytes32 flushhash, address[] tosend, uint[] amount) public { //tosend is array of [blk,add,amt]
require(have(curNodeList, msg.sender));
require(tosend.length == amount.length);
bytes32 hash = sha3(flushhash, tosend, amount);
if( task[hash].distDone) return;
if(!have(task[hash].voters, msg.sender)) {
task[hash].voters.push(msg.sender);
if(task[hash].voters.length > curNodeList.length/2 ) {
//distribute
task[hash].distDone = true;
for(uint i=0; i<tosend.length; i++ ) {
tosend[i].transfer(amount[i]);
}
}
}
}
}
contract DeChat is DappBase{
struct topic {
bytes32 hash;
address owner;
string desc;
uint award;
uint startblk;
uint expblk;
uint bestVoteCount;
bytes32 bestHash;
uint secondBestVoteCount;
bytes32 secondBestHash;
bool closed;
}
struct subTopic {
bytes32 hash;
address owner;
string desc;
uint reward;
bytes32 parent;
uint voteCount;
address[] voters;
}
mapping(bytes32 => topic) public topics;
mapping(bytes32 => subTopic) public subTopics;
mapping(bytes32 => bytes32[]) public topicAns; // main topic => [ans1, ans2,...]
mapping(uint => bytes32[]) public expinfo;
mapping(bytes32 => uint) public voteinfo; // (address,topichash) => 0,1
bytes32[] public newTopicList;
mapping(bytes32 => uint ) newTopicIndex;
uint public lastProcBlk;
uint public answerBond = 10 ** 17; // 0.1
uint public firstPrize = 50; //
uint public secondPrize = 20; //
uint public votePrize = 20; //
uint public modPrize = 9;
uint public devPrize = 1;
uint public voteAwardCount = 100; //only first 100 voter get reward
uint public maxExpBlk = 50;
address internal owner;
address internal developer;
address internal moderator;
mapping(address => topic[]) public myTopics; // index = 0x18
function DeChat(address mod, address dev) public payable {
lastProcBlk = block.number;
owner = msg.sender;
moderator = mod;
developer = dev;
}
function createTopic(uint award, uint expblk, string desc) public payable returns (bytes32) {
require(msg.value >= award );
bytes32 hash = sha3(block.number, msg.sender, desc);
topics[hash].hash = hash;
topics[hash].owner = msg.sender;
topics[hash].award = award;
if( expblk < maxExpBlk) {
topics[hash].expblk = expblk;
} else {
topics[hash].expblk = maxExpBlk;
}
topics[hash].startblk = block.number;
topics[hash].desc = desc;
//add loop value
expinfo[block.number + expblk].push(hash);
newTopicIndex[hash]=newTopicList.length;
newTopicList.push(hash);
myTopics[msg.sender].push(topics[hash]);
return hash;
}
function voteOnTopic(bytes32 topichash) public returns(bytes32) {
require(subTopics[topichash].hash != "");
bytes32 parenthash = subTopics[topichash].parent;
require(parenthash != "" );
//key is (topic, msg.sender)
bytes32 key = sha3(msg.sender, parenthash);
if (voteinfo[key] >= 1){
return bytes32(0);
}
//mark as voted
voteinfo[key] = 1;
//add to voters
subTopics[topichash].voteCount ++;
if(subTopics[topichash].voteCount < voteAwardCount ) {
subTopics[topichash].voters.push(msg.sender);
}
if( subTopics[topichash].voteCount > topics[parenthash].bestVoteCount ) {
//swap best and secnd best
topics[parenthash].secondBestHash = topics[parenthash].bestHash;
topics[parenthash].secondBestVoteCount = topics[parenthash].bestVoteCount;
topics[parenthash].bestHash = topichash;
topics[parenthash].bestVoteCount = subTopics[topichash].voteCount;
updateMyTopic(topics[parenthash]);
return key;
}
if( subTopics[topichash].voteCount > topics[parenthash].secondBestVoteCount ) {
//replace secnd best
topics[parenthash].secondBestHash = topichash;
topics[parenthash].secondBestVoteCount = subTopics[topichash].voteCount;
updateMyTopic(topics[parenthash]);
return key;
}
return key;
}
function creatSubTopic(bytes32 parenthash, string desc) public payable returns (bytes32) {
require(msg.value >= answerBond );
bytes32 hash = sha3(block.number, msg.sender, desc);
//save subtopic
subTopics[hash].hash = hash;
subTopics[hash].owner = msg.sender;
subTopics[hash].desc = desc;
subTopics[hash].reward = 0;
subTopics[hash].parent = parenthash;
//add to ans list
topicAns[parenthash].push(hash);
return hash;
}
function updateMyTopic(topic t) private{
require(t.owner != address(0));
for (uint i=0; i < myTopics[t.owner].length; i++) {
if (t.owner == myTopics[t.owner][i].owner && t.hash == myTopics[t.owner][i].hash) {
myTopics[t.owner][i] = t;
}
}
}
function getMyTopic(address addr) public view returns (topic[]){
require(addr != address(0));
return myTopics[addr];
}
function autoCheck() public {
require ( lastProcBlk < block.number );
for( uint i=lastProcBlk; i<block.number; i++ ) {
for( uint j=0; j<expinfo[i].length; j++ ) {
bytes32 phash = expinfo[i][j];
if(phash == "" || topics[phash].closed) {
continue;
}
//best topic
bytes32 besthash = topics[phash].bestHash;
if(subTopics[besthash].owner != address(0) ){
uint reward1 = topics[phash].award * firstPrize /100;
subTopics[besthash].owner.transfer(reward1);
subTopics[besthash].reward = reward1;
}
//award each voter for besthash
for( uint k=0; k<subTopics[besthash].voters.length; k++ ) {
subTopics[besthash].voters[k].transfer( topics[phash].award * votePrize /100/subTopics[besthash].voters.length );
}
//second best topic
bytes32 secondBesthash = topics[phash].secondBestHash;
if(subTopics[secondBesthash].owner != address(0) ){
uint reward2 = topics[phash].award * secondPrize /100;
subTopics[secondBesthash].owner.transfer(reward2);
subTopics[secondBesthash].reward = reward2;
}
// award moderator
if(moderator != address(0) ){
moderator.transfer( topics[phash].award * modPrize /100 );
}
// award developer
if(developer != address(0) ){
developer.transfer( topics[phash].award * devPrize /100 );
}
//mark as closed
topics[phash].closed = true;
updateMyTopic(topics[phash]);
//swap with last one
bytes32 last = newTopicList[newTopicList.length -1 ];
uint cur = newTopicIndex[phash];
newTopicList[cur] = last;
newTopicIndex[last] = cur;
newTopicList.length --;
delete newTopicIndex[phash];
}
}
}
} | key is (topic, msg.sender)swap best and secnd bestreplace secnd best | function voteOnTopic(bytes32 topichash) public returns(bytes32) {
require(subTopics[topichash].hash != "");
bytes32 parenthash = subTopics[topichash].parent;
require(parenthash != "" );
bytes32 key = sha3(msg.sender, parenthash);
if (voteinfo[key] >= 1){
return bytes32(0);
}
if(subTopics[topichash].voteCount < voteAwardCount ) {
subTopics[topichash].voters.push(msg.sender);
}
if( subTopics[topichash].voteCount > topics[parenthash].bestVoteCount ) {
topics[parenthash].secondBestHash = topics[parenthash].bestHash;
topics[parenthash].secondBestVoteCount = topics[parenthash].bestVoteCount;
topics[parenthash].bestHash = topichash;
topics[parenthash].bestVoteCount = subTopics[topichash].voteCount;
updateMyTopic(topics[parenthash]);
return key;
}
if( subTopics[topichash].voteCount > topics[parenthash].secondBestVoteCount ) {
topics[parenthash].secondBestHash = topichash;
topics[parenthash].secondBestVoteCount = subTopics[topichash].voteCount;
updateMyTopic(topics[parenthash]);
return key;
}
return key;
}
| 7,282,536 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./OwnedRanges.sol";
interface IERC2309 {
event ConsecutiveTransfer(uint indexed fromTokenId, uint toTokenId, address indexed fromAddress, address indexed toAddress);
event TransferForLots(uint fromTokenId, uint toTokenId, address indexed fromAddress, address indexed toAddress);
}
/*
function _init(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
function _transferFotLots(address to, uint fromTokenId, uint toTokenId) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit TransferForLots(fromTokenId, toTokenId, msg.sender, to);
}
*/
contract NFTsERC2309 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, IERC2309 {
using SafeMath for uint;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint;
using OwnedRanges for OwnedRanges.OwnedRangesMapping;
// Equals to `bytes4(keccak("onERC721Received(address,address,uint,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
OwnedRanges.OwnedRangesMapping private owners;
// Mapping from token ID to approved address
mapping (uint => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Optional mapping for token URIs
mapping (uint => string) private _tokenURIs;
string private _name;
string private _symbol;
// Base URI
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
address public contractOwner;
modifier onlyOwner() {
require(msg.sender == contractOwner, "require is not owner");
_;
}
// **************************************
// ************ CONSTRUCTOR *************
// **************************************
constructor (string memory name_, string memory symbol_, uint cant, string memory baseURI_) {
_name = name_;
_symbol = symbol_;
contractOwner = msg.sender;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
_init(msg.sender, cant);
_setBaseURI(baseURI_);
}
//IERC721-balanceOf
function balanceOf(address owner) public view virtual override returns(uint) {
require(owner != address(0), "ERC721: balance query for the zero address");
return owners.ownerBalance(owner);
}
//IERC721-ownerOf
function ownerOf(uint tokenId) public view virtual override returns(address) {
//(bool success, bytes32 value) = _tokenOwners.tryGet(tokenId)
//return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
return owners.ownerOf(tokenId);
}
//IERC721Metadata-name
function name() public view virtual override returns(string memory) {
return _name;
}
//IERC721Metadata-symbol
function symbol() public view virtual override returns(string memory) {
return _symbol;
}
//IERC721Metadata-tokenURI
function tokenURI(uint tokenId) public view virtual override returns(string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
//returnsthe base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI
function baseURI() public view virtual returns(string memory) {
return _baseURI;
}
/*returnsthe base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI
function setbaseURI(string memory baseURI) public virtual returns(string bool) {
return true;
}
*/
//IERC721Enumerable-tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint index) public view virtual override returns(uint) {
return owners.ownedIndexToIdx(owner, index);
}
//IERC721Enumerable-totalSupply
function totalSupply() public view virtual override returns(uint) {
// _tokenOwners are indexed by tokenIds, so .length() returnsthe number of tokenIds
return owners.length();
}
//IERC721Enumerable-tokenByIndex
function tokenByIndex(uint index) public view virtual override returns(uint) {
return index;
}
//IERC721-approve
function approve(address to, uint tokenId) public virtual override {
address owner = NFTsERC2309.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || NFTsERC2309.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
//IERC721-getApproved
function getApproved(uint tokenId) public view virtual override returns(address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
//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);
}
//IERC721-isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns(bool) {
//return _operatorApprovals[owner][operator];
require(!_operatorApprovals[owner][operator]);
return true;
}
//IERC721-transferFrom
function transferFrom(address from, address to, uint tokenId) public virtual onlyOwner override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
//IERC721-safeTransferFrom
function safeTransferFrom(address from, address to, uint tokenId) public virtual onlyOwner override {
safeTransferFrom(from, to, tokenId, "");
}
//IERC721-safeTransferFrom
function safeTransferFrom(address from, address to, uint tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
//Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
//`_data` is additional data, it has no specified format and it is sent in call to `to`.
function _safeTransfer(address from, address to, uint tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
//returnswhether `tokenId` exists.
//Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
function _exists(uint tokenId) internal view virtual returns(bool) {
return owners.length() > tokenId;
}
//returnswhether `spender` is allowed to manage `tokenId`.
function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns(bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = NFTsERC2309.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || NFTsERC2309.isApprovedForAll(owner, spender));
}
//Safely mints `tokenId` and transfers it to `to`.
function _safeMint(address to, uint tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
//Same as ERC721-_safeMint-address-uint-}[`_safeMint`] with an additional `data` parameter which is
function _safeMint(address to, uint tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
//Mints `tokenId` and transfers it to `to`, but usage of this method is discouraged, use {_safeMint} whenever possible
function _mint(address to, uint 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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
// Burn `tokenId`.
function _burn(uint tokenId) internal virtual {
address owner = ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
//Transfers `tokenId` from `from` to `to`.
//As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
function _transfer(address from, address to, uint tokenId) internal virtual {
require(NFTsERC2309.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
owners.setOwner(tokenId, to);
emit Transfer(from, to, tokenId);
}
//Sets `_tokenURI` as the tokenURI of `tokenId`.
function _setTokenURI(uint tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
//Internal function to set the base URI for all token IDs
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_ ;
}
//Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
function _checkOnERC721Received(address from, address to, uint tokenId, bytes memory _data)
private returns(bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(NFTsERC2309.ownerOf(tokenId), to, tokenId); // internal owner
}
//Hook that is called before any token transfer. This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint tokenId) internal virtual { }
function _init(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
/*
function _transferFotLots(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
*/
} | Mints `tokenId` and transfers it to `to`, but usage of this method is discouraged, use {_safeMint} whenever possible | function _mint(address to, uint 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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
| 12,948,066 |
./full_match/3/0x6165744662Ec03C05cA19aCb6a398Ec4309e1258/sources/Kyc.sol | Checks whether the requestor is admin | modifier isAdmin {
require(
admin == msg.sender,
"Only admin is allowed to operate this functionality"
);
_;
}
| 8,244,768 |
pragma solidity ^0.4.24;
import "zeppelin/math/SafeMath.sol";
/**
* @notice Additional math operations
**/
library AdditionalMath {
using SafeMath for uint256;
function max16(uint16 a, uint16 b) internal pure returns (uint16) {
return a >= b ? a : b;
}
function min16(uint16 a, uint16 b) internal pure returns (uint16) {
return a < b ? a : b;
}
/**
* @notice Division and ceil
**/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return (a.add(b) - 1) / b;
}
/**
* @dev Adds unsigned value to signed value, throws on overflow.
*/
function add(int256 a, uint256 b) internal pure returns (int256) {
int256 c = a + int256(b);
assert(c >= a);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow.
*/
function sub(int256 a, uint256 b) internal pure returns (int256) {
int256 c = a - int256(b);
assert(c <= a);
return c;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function add(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.add(uint256(b));
} else {
return a.sub(uint256(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function sub(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.sub(uint256(b));
} else {
return a.add(uint256(-b));
}
}
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul32(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add16(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub16(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
}
| Adds signed value to unsigned value, throws on overflow./ | function add(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.add(uint256(b));
return a.sub(uint256(-b));
}
}
| 13,120,596 |
./full_match/4/0x9C6E280f720DE8FeB11A04F5a1c842847520fbCF/sources/npcNFT.sol | OZ HELPERS | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
_moveDelegates(delegates[from], delegates[to], 1);
super._beforeTokenTransfer(from, to, tokenId);
}
| 766,924 |
pragma solidity 0.4.26;
import "./copied/amm/converter/types/liquidity-pool-v2/LiquidityPoolV2Converter.sol";
/**
* @dev Improved testing version of the liquidity Pool v2 Converter
*
* This builds on top of oracle-based-amm/solidity/contracts/helpers/TestLiquidityPoolV2Converter.sol
* but adds methods for setting the reserve balances without affecting staked balances, and for doing other useful
* development stuff.
* This way, we can initialize the contract to any state we want in unit tests.
*
* It should go without saying, but:
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !! DO NOT UNDER ANY CIRCUMSTANCE DEPLOY THIS CONTRACT TO PRODUCTION. !!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* The nature of the contract means that anyone can can retrieve all tokens at will.
*/
contract ImprovedTestLiquidityPoolV2Converter is LiquidityPoolV2Converter {
uint256 public currentTime;
constructor(
IPoolTokensContainer _token,
IContractRegistry _registry,
uint32 _maxConversionFee
) public LiquidityPoolV2Converter(_token, _registry, _maxConversionFee) {}
function setReferenceRateUpdateTime(uint256 _referenceRateUpdateTime) public {
referenceRateUpdateTime = _referenceRateUpdateTime;
}
function time() internal view returns (uint256) {
return currentTime != 0 ? currentTime : now;
}
function setTime(uint256 _currentTime) public {
currentTime = _currentTime;
}
function calculateFeeToEquilibriumTest(
uint256 _primaryReserveStaked,
uint256 _secondaryReserveStaked,
uint256 _primaryReserveWeight,
uint256 _secondaryReserveWeight,
uint256 _primaryReserveRate,
uint256 _secondaryReserveRate,
uint256 _dynamicFeeFactor
) external pure returns (uint256) {
return
calculateFeeToEquilibrium(
_primaryReserveStaked,
_secondaryReserveStaked,
_primaryReserveWeight,
_secondaryReserveWeight,
_primaryReserveRate,
_secondaryReserveRate,
_dynamicFeeFactor
);
}
function setReserveWeight(IERC20Token _reserveToken, uint32 _weight) public validReserve(_reserveToken) {
reserves[_reserveToken].weight = _weight;
}
/**
* @dev transfers tokens from sender to the contract, increasing reserve balance
* without affecting staked balance
* the sender needs to approve the contract to spend tokens first
*
* @param _reserveToken reserve token, the reserve balance of which to increase
* @param _amount amount of tokens to transfer/balance to increase
*/
function addToReserveBalance(IERC20Token _reserveToken, uint256 _amount) public validReserve(_reserveToken) {
_reserveToken.transferFrom(msg.sender, address(this), _amount);
reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount);
}
/**
* @dev transfers tokens from the contract to the sender, decreasing reserve balance
* without affecting staked balance
*
* @param _reserveToken reserve token, the reserve balance of which to decrease
* @param _amount amount of tokens to transfer/balance to decrease
*/
function subtractFromReserveBalance(IERC20Token _reserveToken, uint256 _amount) public validReserve(_reserveToken) {
require(reserves[_reserveToken].balance >= _amount, "ERR_RESERVE_BALANCE_WOULD_BECOME_NEGATIVE");
_reserveToken.transfer(msg.sender, _amount);
reserves[_reserveToken].balance = reserves[_reserveToken].balance.sub(_amount);
}
/**
* @dev transfers tokens to/from the contract, increasing/decreasing the reserve balance to the desired balance
* without affecting staked balance.
* the sender should approve the contract to spend tokens first, in case tokens are transferred to
* the contract.
*
* @param _reserveToken reserve token, the reserve balance of which to increase or decrease
* @param _balance desired reserve balance for the contract
*/
function setReserveBalance(IERC20Token _reserveToken, uint256 _balance) public validReserve(_reserveToken) {
uint256 reserveBalance = reserves[_reserveToken].balance;
if(_balance > reserveBalance) {
addToReserveBalance(_reserveToken, _balance.sub(reserveBalance));
} else if (_balance < reserveBalance) {
subtractFromReserveBalance(_reserveToken, reserveBalance.sub(_balance));
}
}
/**
* @dev updates reference rate and update times from priceOracle.
* does not rebalance weights
*/
function updateRateAndTimeFromPriceOracle() public {
(uint256 oracleRateN, uint256 oracleRateD, uint256 oracleUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
currentTime = oracleUpdateTime;
referenceRateUpdateTime = currentTime - 1 seconds;
referenceRate = Fraction({ n: oracleRateN, d: oracleRateD });
}
/**
* @dev forces rebalancing of weights according to the reference rate
*/
function forceRebalance() public {
// get the new reserve weights
(uint256 primaryReserveWeight, uint256 secondaryReserveWeight) = effectiveReserveWeights();
// update the reserve weights with the new values
reserves[primaryReserveToken].weight = uint32(primaryReserveWeight);
reserves[secondaryReserveToken].weight = uint32(secondaryReserveWeight);
}
}
| transfers tokens to/from the contract, increasing/decreasing the reserve balance to the desired balance without affecting staked balance. the sender should approve the contract to spend tokens first, in case tokens are transferred to the contract. _reserveToken reserve token, the reserve balance of which to increase or decrease _balance desired reserve balance for the contract/ | function setReserveBalance(IERC20Token _reserveToken, uint256 _balance) public validReserve(_reserveToken) {
uint256 reserveBalance = reserves[_reserveToken].balance;
if(_balance > reserveBalance) {
addToReserveBalance(_reserveToken, _balance.sub(reserveBalance));
subtractFromReserveBalance(_reserveToken, reserveBalance.sub(_balance));
}
}
| 12,961,615 |
./partial_match/1/0x45eDb535942a8C84D9f4b5D37e1b25F91Ea4804c/sources/RAOToken.sol | Check the allowed value for the spender to withdraw from owner owner The address of the owner spender The address of the spender return the amount which spender is still allowed to withdraw from owner | function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
| 4,424,887 |
./full_match/1/0xDbadeFb972132C82BE8601Fa7b9Ba4801262271d/sources/@exoda/contracts/token/ERC20/ERC20.sol | 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) override public virtual returns (bool)
{
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
| 16,409,163 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./interfaces/IDeFiatPoints.sol";
import "./lib/@openzeppelin/token/ERC20/ERC20.sol";
import "./utils/DeFiatGovernedUtils.sol";
contract DeFiatPoints is ERC20("DeFiat Points v2", "DFTPv2"), IDeFiatPoints, DeFiatGovernedUtils {
using SafeMath for uint256;
event DiscountUpdated(address indexed user, uint256 discount);
event TrancheUpdated(address indexed user, uint256 tranche, uint256 pointsNeeded);
event AllTranchesUpdated(address indexed user);
event TokenUpdated(address indexed user, address token);
event PointsUpdated(address indexed user, address indexed subject, uint256 amount);
event WhitelistedUpdated(address indexed user, address indexed subject, bool whitelist);
event RedirectionUpdated(address indexed user, address indexed subject, bool redirect);
address public token; // DFT ERC20 Token
mapping (uint256 => uint256) public discountTranches; // mapping of DFTP needed for each discount tranche
mapping (address => uint256) private _discounts; // mapping of users to current discount, 100 = 100%
mapping (address => uint256) private _lastTx; // mapping of users last txn
mapping (address => bool) private _whitelisted; // mapping of addresses who are allowed to call addPoints
mapping (address => bool) private _redirection; // addresses where points should be redirected to tx.origin, i.e. uniswap
constructor(address _governance) public {
_setGovernance(_governance);
_mint(msg.sender, 150000 * 1e18);
}
// Views
// Discounts - View the current % discount of the _address
function viewDiscountOf(address _address) public override view returns (uint256) {
return _discounts[_address];
}
// Discounts - View the discount level the _address is eligibile for
function viewEligibilityOf(address _address) public override view returns (uint256 tranche) {
uint256 balance = balanceOf(_address);
for (uint256 i = 0; i <= 9; i++) {
if (balance >= discountTranches[i]) {
tranche = i;
} else {
return tranche;
}
}
}
// Discounts - Check amount of points needed for _tranche
function discountPointsNeeded(uint256 _tranche) public override view returns (uint256 pointsNeeded) {
return (discountTranches[_tranche]);
}
// Points - Min amount
function viewTxThreshold() public override view returns (uint256) {
return IDeFiatGov(governance).viewTxThreshold();
}
// Points - view whitelisted address
function viewWhitelisted(address _address) public override view returns (bool) {
return _whitelisted[_address];
}
// Points - view redirection address
function viewRedirection(address _address) public override view returns (bool) {
return _redirection[_address];
}
// State-Changing Functions
// Discount - Update Discount internal function to control event on every update
function _updateDiscount(address user, uint256 discount) internal {
_discounts[user] = discount;
emit DiscountUpdated(user, discount);
}
// Discount - Update your discount if balance of DFTP is high enough
// Otherwise, throw to prevent unnecessary calls
function updateMyDiscount() public returns (bool) {
uint256 tranche = viewEligibilityOf(msg.sender);
uint256 discount = tranche * 10;
require(discount != _discounts[msg.sender], "UpdateDiscount: No discount change");
_updateDiscount(msg.sender, discount);
}
// Discount - Update the user discount directly, Governance-Only
function overrideDiscount(address user, uint256 discount) external onlyGovernor {
require(discount <= 100, "OverrideDiscount: Must be in-bounds");
require(_discounts[user] != discount, "OverrideDiscount: No discount change");
_updateDiscount(user, discount);
}
// Tranches - Set an individual discount tranche
function setDiscountTranches(uint256 tranche, uint256 pointsNeeded) external onlyGovernor {
require(tranche < 10, "SetTranche: Maximum tranche level exceeded");
require(discountTranches[tranche] != pointsNeeded, "SetTranche: No change detected");
discountTranches[tranche] = pointsNeeded;
emit TrancheUpdated(msg.sender, tranche, pointsNeeded);
}
// Tranches - Set all 10 discount tranches
function setAll10DiscountTranches(
uint256 _pointsNeeded1, uint256 _pointsNeeded2, uint256 _pointsNeeded3, uint256 _pointsNeeded4,
uint256 _pointsNeeded5, uint256 _pointsNeeded6, uint256 _pointsNeeded7, uint256 _pointsNeeded8,
uint256 _pointsNeeded9
) external onlyGovernor {
discountTranches[0] = 0;
discountTranches[1] = _pointsNeeded1; // 10%
discountTranches[2] = _pointsNeeded2; // 20%
discountTranches[3] = _pointsNeeded3; // 30%
discountTranches[4] = _pointsNeeded4; // 40%
discountTranches[5] = _pointsNeeded5; // 50%
discountTranches[6] = _pointsNeeded6; // 60%
discountTranches[7] = _pointsNeeded7; // 70%
discountTranches[8] = _pointsNeeded8; // 80%
discountTranches[9] = _pointsNeeded9; // 90%
emit AllTranchesUpdated(msg.sender);
}
// Points - Update the user DFTP balance, Governance-Only
function overrideLoyaltyPoints(address _address, uint256 _points) external override onlyGovernor {
uint256 balance = balanceOf(_address);
if (balance == _points) {
return;
}
_burn(_address, balance);
if (_points > 0) {
_mint(_address, _points);
}
emit PointsUpdated(msg.sender, _address, _points);
}
// Points - Add points to the _address when the _txSize is greater than txThreshold
// Only callable by governors
function addPoints(address _address, uint256 _txSize, uint256 _points) external onlyGovernor {
if (!_whitelisted[msg.sender]) {
return;
}
if(_txSize >= viewTxThreshold() && _lastTx[tx.origin] < block.number){
if (_redirection[_address]) {
_mint(tx.origin, _points);
} else {
_mint(_address, _points);
}
_lastTx[tx.origin] = block.number;
}
}
// Points - Override to force update user discount on every transfer
// Note: minting/burning does not constitute as a transfer, so we must have the update function
function _transfer(address sender, address recipient, uint256 amount) internal override {
ERC20._transfer(sender, recipient, amount);
// force update discount if not governance
if (IDeFiatGov(governance).viewActorLevelOf(sender) == 0) {
uint256 tranche = viewEligibilityOf(sender);
_discounts[sender] = tranche * 10;
}
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
// Gov - Set whitelist address
function setWhitelisted(address _address, bool _whitelist) external override onlyGovernor {
require(_whitelisted[_address] != _whitelist, "SetWhitelisted: No whitelist change");
_whitelisted[_address] = _whitelist;
emit WhitelistedUpdated(msg.sender, _address, _whitelist);
}
// Gov - Set redirection address
function setRedirection(address _address, bool _redirect) external override onlyGovernor {
require(_redirection[_address] != _redirect, "SetRedirection: No redirection change");
_redirection[_address] = _redirect;
emit RedirectionUpdated(msg.sender, _address, _redirect);
}
// Gov - Update the DeFiat Token address
function setToken(address _token) external onlyGovernor {
require(_token != token, "SetToken: No token change");
token = _token;
emit TokenUpdated(msg.sender, token);
}
}
| Points - view redirection address | function viewRedirection(address _address) public override view returns (bool) {
return _redirection[_address];
}
| 974,282 |
/* HTTPS://SYNCBOND.COM HTTPS://APP.SYNCBOND.COM
███████╗██╗░░░██╗███╗░░░██╗░██████╗░░░░██████╗░░██████╗░██╗░░░░██╗███████╗██████╗░███████╗██████╗░
██╔════╝╚██╗░██╔╝████╗░░██║██╔════╝░░░░██╔══██╗██╔═══██╗██║░░░░██║██╔════╝██╔══██╗██╔════╝██╔══██╗
███████╗░╚████╔╝░██╔██╗░██║██║░░░░░░░░░██████╔╝██║░░░██║██║░█╗░██║█████╗░░██████╔╝█████╗░░██║░░██║
╚════██║░░╚██╔╝░░██║╚██╗██║██║░░░░░░░░░██╔═══╝░██║░░░██║██║███╗██║██╔══╝░░██╔══██╗██╔══╝░░██║░░██║
███████║░░░██║░░░██║░╚████║╚██████╗░░░░██║░░░░░╚██████╔╝╚███╔███╔╝███████╗██║░░██║███████╗██████╔╝
╚══════╝░░░╚═╝░░░╚═╝░░╚═══╝░╚═════╝░░░░╚═╝░░░░░░╚═════╝░░╚══╝╚══╝░╚══════╝╚═╝░░╚═╝╚══════╝╚═════╝░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░██████╗██████╗░██╗░░░██╗██████╗░████████╗░██████╗░██████╗░░██████╗░███╗░░░██╗██████╗░███████╗░░░░
██╔════╝██╔══██╗╚██╗░██╔╝██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗██╔═══██╗████╗░░██║██╔══██╗██╔════╝░░░░
██║░░░░░██████╔╝░╚████╔╝░██████╔╝░░░██║░░░██║░░░██║██████╔╝██║░░░██║██╔██╗░██║██║░░██║███████╗░░░░
██║░░░░░██╔══██╗░░╚██╔╝░░██╔═══╝░░░░██║░░░██║░░░██║██╔══██╗██║░░░██║██║╚██╗██║██║░░██║╚════██║░░░░
╚██████╗██║░░██║░░░██║░░░██║░░░░░░░░██║░░░╚██████╔╝██████╔╝╚██████╔╝██║░╚████║██████╔╝███████║░░░░
░╚═════╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░░░░░░░╚═╝░░░░╚═════╝░╚═════╝░░╚═════╝░╚═╝░░╚═══╝╚═════╝░╚══════╝░░░░
*/
pragma solidity ^0.6.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);
}
interface ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes calldata data) external;
}
/**
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev 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;
}
}
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
library SquareRoot {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
/*
https://ethereum.stackexchange.com/a/8447
*/
library AddressStrings {
function toString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(byte b) internal pure returns (byte c) {
if (uint8(b) < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
}
interface Oracle{
function liquidityValues(address token) external view returns(uint);//returns usd value of token (consider usd an 18 decimal stablecoin), or 0 if not listed
function syncValue() external view returns(uint);//returns usd value of SYNC
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered 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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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));
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 mecanisms 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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 = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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 { }
}
/**
* @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 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;
}
}
contract Sync is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
string public constant name = "SYNC";
string public constant symbol = "SYNC";
uint8 public constant decimals = 18;
uint256 _totalSupply = 16000000 * (10 ** 18); // 16 million supply
mapping (address => bool) public mintContracts;
modifier isMintContract() {
require(mintContracts[msg.sender],"calling address is not allowed to mint");
_;
}
constructor() public Ownable(){
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function setMintAccess(address account, bool canMint) public onlyOwner {
mintContracts[account]=canMint;
}
function _mint(address account, uint256 amount) public isMintContract {
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);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address user) public view override returns (uint256) {
return balances[user];
}
function allowance(address user, address spender) public view override returns (uint256) {
return allowed[user][spender];
}
function transfer(address to, uint256 value) public override returns (bool) {
require(value <= balances[msg.sender],"insufficient balance");
require(to != address(0),"cannot send to zero address");
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public override returns (bool) {
require(spender != address(0),"cannot approve the zero address");
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
require(value <= balances[from],"insufficient balance");
require(value <= allowed[from][msg.sender],"insufficient allowance");
require(to != address(0),"cannot send to the zero address");
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;
}
function burn(uint256 amount) external {
require(amount != 0,"must burn more than zero");
require(amount <= balances[msg.sender],"insufficient balance");
_totalSupply = _totalSupply.sub(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
emit Transfer(msg.sender, address(0), amount);
}
}
contract CBOND is ERC721, Ownable {
using SafeMath for uint256;
using Strings for uint256;
using AddressStrings for address;
event Created(address token,uint256 syncAmount,uint256 tokenAmount,uint256 syncPrice,uint256 tokenPrice,uint256 tokenId);
event Matured(address token,uint256 syncReturned,uint256 tokenAmount,uint256 tokenId);
event DivsPaid(address token,uint256 syncReturned,uint256 tokenId);
//read only counter values
uint256 public totalCBONDS=0;//Total number of Cbonds created.
uint256 public totalQuarterlyCBONDS=0;//Total number of quarterly Cbonds created.
uint256 public totalCBONDSCashedout=0;//Total number of Cbonds that have been matured.
uint256 public totalSYNCLocked=0;//Total amount of Sync locked in Cbonds.
mapping(address => uint256) public totalLiquidityLockedByPair;//Total amount of tokens locked in Cbonds of the given liquidity token.
//values contained in individual CBONDs, by token id
mapping(uint256 => address) public lAddrById;//The address of the liquidity token used to create the given Cbond.
mapping(uint256 => uint256) public lTokenPriceById;//The relative price of the liquidity token at the time the given Cbond was created.
mapping(uint256 => uint256) public lTokenAmountById;//The amount of liquidity tokens initially deposited into the given Cbond.
mapping(uint256 => uint256) public syncPriceById;//The relative price of Sync at the time the given Cbond was created.
mapping(uint256 => uint256) public syncAmountById;//The amount of Sync initially deposited into the given Cbond.
mapping(uint256 => uint256) public syncInterestById;//The amount of Sync interest on the initially deposited Sync awarded by the given Cbond. For quarterly Cbonds, this variable will represent only the interest of a single quarter.
mapping(uint256 => uint256) public syncRewardedOnMaturity;//The amount of Sync returned to the user on maturation of the given Cbond.
mapping(uint256 => uint256) public timestampById;//The time the given Cbond was created.
mapping(uint256 => bool) public gradualDivsById;//Whether the given Cbond awards dividends quarterly.
mapping(uint256 => uint256) public lastDivsCashoutById;//For Quarterly Cbonds, this variable represents the last cashout timestamp.
mapping(uint256 => uint256) public totalDivsCashoutById;//For Quarterly Cbonds, the total dividends cashed out to date. Frontend use only, not used for calculations within the contract.
mapping(uint256 => uint256) public termLengthById;//Length of term in seconds for the given Cbond.
//constant and pseudo-constant (never changed after constructor) values
uint256 constant public PERCENTAGE_PRECISION=10000;//Divide percentages by this to get the real multiplier.
uint256 constant public INCENTIVE_MAX_PERCENT=220;//2.2%, the maximum value the liquidity incentive rate can be.
uint256 constant public MAX_SYNC_GLOBAL=100000 * (10 ** 18);//Maximum Sync in a Cbond. Cbonds with higher amounts of Sync cannot be created.
uint256 constant public QUARTER_LENGTH=90 days;//The length of a quarter, the interval of time between quarterly dividends.
uint256 public STARTING_TIME=block.timestamp;//The time the contract was deployed.
uint256 constant public BASE_INTEREST_RATE_START=220;//2.2%, starting value for base interest rate.
uint256 constant public MINIMUM_BASE_INTEREST_RATE=10;//0.1%, the minimum value base interest rate can be.
uint256 constant public MAXIMUM_BASE_INTEREST_RATE=4500;//45%, the maximum value base interest rate can be.
uint256[] public LUCKY_EXTRAS=[500,1000];//Bonus interest awarded to user on creating lucky and extra lucky Cbonds.
uint256 public YEAR_LENGTH=360 days;//Time length of approximately 1 year
uint256[] public TERM_DURATIONS=[90 days,180 days,360 days,720 days,1080 days];//Possible term durations for Cbonds, index values corresponding to the following variables:
uint256[] public DURATION_MODIFIERS=[825,1650,3300,6600,10000];//The percentage values used as duration modifiers for the given term lengths.
uint256[] public DURATION_CALC_LOOPS=[0,0,3,7,11];//Number of loops for the duration rate formula approximation function, for the given term duration.
mapping(uint256 => uint256) public INDEX_BY_DURATION;//Mapping of term durations to index values, as relates to the above variables.
uint256 public RISK_FACTOR = 5;//Constant used in duration rate calculation
//Index variables for tracking
uint256 public lastDaySyncSupplyUpdated=0;//The previously recorded day on which the supply of Sync was last recorded into syncSupplyByDay.
uint256 public currentDaySyncSupplyUpdated=0;//The day on which the supply of Sync was last recorded into syncSupplyByDay.
mapping(address => mapping(uint256 => uint256)) public cbondsHeldByUser;//Mapping of cbond ids held by user. The second mapping is a list, length given by cbondsHeldByUserCursor.
mapping(address => uint256) public cbondsHeldByUserCursor;//The number of Cbonds held by the given user.
mapping(address => uint256) public lastDayTokenSupplyUpdated;//The previously recorded day on which the supply of the given token was last recorded into liqTokenTotalsByDay.
mapping(address => uint256) public currentDayTokenSupplyUpdated;//The day on which the supply of the given token was last recorded into liqTokenTotalsByDay.
mapping(uint256 => uint256) public syncSupplyByDay;//The recorded total supply of the Sync token for the given day. This value is written once and thereafter cannot be changed for a given day.
mapping(uint256 => uint256) public interestRateByDay;//The recorded base interest rate for the given day. This value is written once and thereafter cannot be changed for a given day, and is recorded simultaneously with syncSupplyByDay.
mapping(address => mapping(uint256 => uint256)) public liqTokenTotalsByDay;//The recorded total for the given liquidity token on the given day. This value is written once and thereafter cannot be changed for a given token/day.
uint256 public _currentTokenId = 0;//Variable for tracking next NFT identifier.
//Read only tracking variables (not used within the smart contract)
mapping(uint256 => uint256) public cbondsMaturingByDay;//Mapping of days to number of cbonds maturing that day.
//admin adjustable values
mapping(address => bool) public tokenAccepted;//Whether a given liquidity token has been approved for use by admins. Cbonds can only be created using tokens listed here.
uint256 public syncMinimum = 25 * (10 ** 18);//Cbonds cannot be created unless at least this amount of Sync is being included in them.
bool public luckyEnabled = true;//Whether it is possible to create Lucky Cbonds
//external contracts
Oracle public priceChecker;//Used to determine the ratio in price between Sync and a given liquidity token. The value returned should not significantly affect user incentives and does not need to be guaranteed not to be exploitable by the user. Contract can be replaced by admin.
Sync syncToken;//The Sync token contract. Sync is contained in every Cbond and is minted to provide interest on Cbonds.
constructor(Oracle o,Sync s) public Ownable() ERC721("CBOND","CBOND"){
priceChecker=o;
syncToken=s;
syncSupplyByDay[0]=syncToken.totalSupply();
interestRateByDay[0]=BASE_INTEREST_RATE_START;
_setBaseURI("api.syncbond.com");
for(uint256 i=0;i<TERM_DURATIONS.length;i++){
INDEX_BY_DURATION[TERM_DURATIONS[i]]=i;
}
}
/*
Admin functions
*/
/*
Admin function to set the base URI for metadata access.
*/
function setBaseURI(string calldata baseURI_) external onlyOwner{
_setBaseURI(baseURI_);
}
/*
Admin function to set liquidity tokens which may be used to create Cbonds.
*/
function setLiquidityTokenAccepted(address token,bool accepted) external onlyOwner{
tokenAccepted[token]=accepted;
}
/*
Admin function to set liquidity tokens which may be used to create Cbonds.
*/
function setLiquidityTokenAcceptedMulti(address[] calldata tokens,bool accepted) external onlyOwner{
for(uint256 i=0;i<tokens.length;i++){
tokenAccepted[tokens[i]]=accepted;
}
}
/*
Admin function to reduce the minimum amount of Sync that can be used to create a Cbond.
*/
function setSyncMinimum(uint256 newMinimum) public onlyOwner{
require(newMinimum<syncMinimum,"increasing minimum sync required is not permitted");
syncMinimum=newMinimum;
}
/*
Admin function to change the price oracle.
*/
function setPriceOracle(Oracle o) external onlyOwner{
priceChecker=o;
}
/*
Admin function to toggle on/off the lucky bonus.
*/
function toggleLuckyBonus(bool enabled) external onlyOwner{
luckyEnabled=enabled;
}
/*
Admin function for updating the daily Sync total supply and token supply for various tokens, for use in case of low activity.
*/
function recordSyncAndTokens(address[] calldata tokens) external onlyOwner{
recordSyncSupply();
for(uint256 i=0;i<tokens.length;i++){
recordTokenSupply(tokens[i]);
}
}
/*
Retrieves available dividends for the given token. Dividends accrue every 3 months.
*/
function cashOutDivs(uint256 tokenId) external{
require(msg.sender==ownerOf(tokenId),"only token owner can call this");
require(gradualDivsById[tokenId],"must be in quarterly dividends mode");
//record current Sync supply and liquidity token supply for the day if needed
recordSyncSupply();
recordTokenSupply(lAddrById[tokenId]);
//reward user with appropriate amount. If none is due it will provide an amount of 0 tokens.
uint256 divs=dividendsOf(tokenId);
syncToken._mint(msg.sender,divs);
//register the timestamp of this transaction so future div payouts can be accurately calculated
lastDivsCashoutById[tokenId]=block.timestamp;
//update read variables
totalDivsCashoutById[tokenId]=totalDivsCashoutById[tokenId].add(divs);
emit DivsPaid(lAddrById[tokenId],divs,tokenId);
}
/*
Returns liquidity tokens, mints Sync to pay back initial amount plus rewards.
*/
function matureCBOND(uint256 tokenId) public{
require(msg.sender==ownerOf(tokenId),"only token owner can call this");
require(block.timestamp>termLengthById[tokenId].add(timestampById[tokenId]),"cbond term not yet completed");
//record current Sync supply and liquidity token supply for the day if needed
recordSyncSupply();
recordTokenSupply(lAddrById[tokenId]);
//amount of sync provided to user is initially deposited amount plus interest
uint256 syncRetrieved=syncRewardedOnMaturity[tokenId];
//provide user with their Sync tokens and their initially deposited liquidity tokens
uint256 beforeMint=syncToken.balanceOf(msg.sender);
syncToken._mint(msg.sender,syncRetrieved);
require(IERC20(lAddrById[tokenId]).transfer(msg.sender,lTokenAmountById[tokenId]),"transfer must succeed");
//update read only counter
totalCBONDSCashedout=totalCBONDSCashedout.add(1);
emit Matured(lAddrById[tokenId],syncRetrieved,lTokenAmountById[tokenId],tokenId);
//burn the nft
_burn(tokenId);
}
/*
Public function for creating a new Cbond.
*/
function createCBOND(address liquidityToken,uint256 amount,uint256 syncMaximum,uint256 secondsInTerm,bool gradualDivs) external returns(uint256){
return _createCBOND(liquidityToken,amount,syncMaximum,secondsInTerm,gradualDivs,msg.sender);
}
/*
Function for creating a new Cbond. User specifies a liquidity token and an amount, this is transferred from their account to this contract, along with a corresponding amount of Sync (transaction reverts if this is greater than the user provided maximum at the time of execution). A permitted term length is also provided, and whether the Cbond should provide gradual divs (Quarterly variety Cbond).
*/
function _createCBOND(address liquidityToken,uint256 amount,uint256 syncMaximum,uint256 secondsInTerm,bool gradualDivs,address sender) private returns(uint256){
require(tokenAccepted[liquidityToken],"liquidity token must be on the list of approved tokens");
//record current Sync supply and liquidity token supply for the day if needed
recordSyncSupply();
recordTokenSupply(liquidityToken);
//determine amount of Sync required, given the amount of liquidity tokens specified, and transfer that amount from the user
uint256 liquidityValue=priceChecker.liquidityValues(liquidityToken);
uint256 syncValue=priceChecker.syncValue();
//Since syncRequired is the exact amount of Sync that will be transferred from the user, integer division truncations propagating to other values derived from this one is the correct behavior.
uint256 syncRequired=liquidityValue.mul(amount).div(syncValue);
require(syncRequired>=syncMinimum,"input tokens too few, sync transferred must be above the minimum");
require(syncRequired<=syncMaximum,"price changed too much since transaction submitted");
require(syncRequired<=MAX_SYNC_GLOBAL,"CBOND amount too large");
syncToken.transferFrom(sender,address(this),syncRequired);
require(IERC20(liquidityToken).transferFrom(sender,address(this),amount),"transfer must succeed");
//burn sync tokens provided
syncToken.burn(syncRequired);
//get the token id of the new NFT
uint256 tokenId=_getNextTokenId();
//set all nft variables
lAddrById[tokenId]=liquidityToken;
syncPriceById[tokenId]=syncValue;
syncAmountById[tokenId]=syncRequired;
lTokenPriceById[tokenId]=liquidityValue;
lTokenAmountById[tokenId]=amount;
timestampById[tokenId]=block.timestamp;
lastDivsCashoutById[tokenId]=block.timestamp;
gradualDivsById[tokenId]=gradualDivs;
termLengthById[tokenId]=secondsInTerm;
//set the interest rate and final maturity withdraw amount
setInterestRate(tokenId,syncRequired,liquidityToken,secondsInTerm,gradualDivs);
//update global counters
cbondsMaturingByDay[getDay(block.timestamp.add(secondsInTerm))]=cbondsMaturingByDay[getDay(block.timestamp.add(secondsInTerm))].add(1);
cbondsHeldByUser[sender][cbondsHeldByUserCursor[sender]]=tokenId;
cbondsHeldByUserCursor[sender]=cbondsHeldByUserCursor[sender].add(1);
totalCBONDS=totalCBONDS.add(1);
totalSYNCLocked=totalSYNCLocked.add(syncRequired);
totalLiquidityLockedByPair[liquidityToken]=totalLiquidityLockedByPair[liquidityToken].add(amount);
//create NFT
_safeMint(sender,tokenId);
_incrementTokenId();
//submit event
emit Created(liquidityToken,syncRequired,amount,syncValue,liquidityValue,tokenId);
return tokenId;
}
/*
Creates a metadata string from a token id. Should not be used onchain.
*/
function putTogetherMetadataString(uint256 tokenId) public view returns(string memory){
//TODO: add the rest of the variables, separate with appropriate url variable separators for ease of use
string memory isDivs=gradualDivsById[tokenId]?"true":"false";
return string(abi.encodePacked("/?tokenId=",tokenId.toString(),"&lAddr=",lAddrById[tokenId].toString(),"&syncPrice=", syncPriceById[tokenId].toString(),"&syncAmount=",syncAmountById[tokenId].toString(),"&mPayout=",syncRewardedOnMaturity[tokenId].toString(),"&lPrice=",lTokenPriceById[tokenId].toString(),"&lAmount=",lTokenAmountById[tokenId].toString(),"&startTime=",timestampById[tokenId].toString(),"&isDivs=",isDivs,"&termLength=",termLengthById[tokenId].toString(),"&divsNow=",dividendsOf(tokenId).toString()));
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
//this line altered from
//string memory _tokenURI = _tokenURIs[tokenId];
//use of gas to manipulate strings can be avoided by putting them together at time of retrieval rather than in the token creation transaction.
string memory _tokenURI = putTogetherMetadataString(tokenId);
// If there is no base URI, return the token URI.
if (bytes(baseURI()).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(baseURI(), _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(baseURI(), tokenId.toString()));
}
/*
Increments a counter used to produce the identifier for the next token to be created.
*/
function _incrementTokenId() private {
_currentTokenId=_currentTokenId.add(1);
}
/*
view functions
*/
/*
Returns the next unused token identifier.
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}
/*
Convenience function to get the current block time directly from the contract.
*/
function getTime() public view returns(uint256){
return block.timestamp;
}
/*
Returns the current dividends owed to the given token, payable to its current owner.
*/
function dividendsOf(uint256 tokenId) public view returns(uint256){
//determine the number of periods worth of divs the token owner is owed, by subtracting the current period by the period when divs were last withdrawn.
require(lastDivsCashoutById[tokenId]>=timestampById[tokenId],"dof1");
uint256 lastCashoutInPeriod=lastDivsCashoutById[tokenId].sub(timestampById[tokenId]).div(QUARTER_LENGTH);//0 - first quarter, 1 - second, etc. This variable also represents the number of quarters previously cashed out
require(block.timestamp>=timestampById[tokenId],"dof2");
uint256 currentCashoutInPeriod=block.timestamp.sub(timestampById[tokenId]).div(QUARTER_LENGTH);
require(currentCashoutInPeriod>=lastCashoutInPeriod,"dof3");
uint256 periodsToCashout=currentCashoutInPeriod.sub(lastCashoutInPeriod);
//only accrue divs before the maturation date. The final div payment will be paid as part of the matureCBOND transaction, so set the maximum number of periods to cash out be one less than the ultimate total.
if(currentCashoutInPeriod>=termLengthById[tokenId].div(90 days)){
//possible for lastCashout period to be greater due to being able to cash out after CBOND has ended (which records lastCashout as being after that date, despite only paying out for earlier periods). In this case, set periodsToCashout to 0 and ultimately return 0, there are no divs left.
if(lastCashoutInPeriod>termLengthById[tokenId].div(90 days).sub(1)){
periodsToCashout=0;
}
else{
periodsToCashout=termLengthById[tokenId].div(90 days).sub(1).sub(lastCashoutInPeriod);
}
}
//multiply the number of periods to pay out with the amount of divs owed for one period. Note: if this is a Quarterly Cbond, syncInterestById will have been recorded as the interest per quarter, rather than the total interest for the Cbond, as with a normal Cbond.
uint quarterlyDividend=syncInterestById[tokenId];
return periodsToCashout.mul(syncAmountById[tokenId]).mul(quarterlyDividend).div(PERCENTAGE_PRECISION);
}
/*
Returns the amount of Sync needed to create a Cbond with the given amount of the given liquidity token. Consults the price oracle for the appropriate ratio.
*/
function getSyncRequiredForCreation(IERC20 liquidityToken,uint256 amount) external view returns(uint256){
return priceChecker.liquidityValues(address(liquidityToken)).mul(amount).div(priceChecker.syncValue());
}
/*
Set the sync rewarded on maturity and interest rate for the given CBOND
*/
function setInterestRate(uint256 tokenId,uint256 syncRequired,address liquidityToken,uint256 secondsInTerm,bool gradualDivs) private{
(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate)=getSuppliesNow(liquidityToken);
(uint256 interestRate,uint256 totalReturn)=getCbondTotalReturn(tokenId,syncRequired,liquidityToken,secondsInTerm,gradualDivs);
syncRewardedOnMaturity[tokenId]=totalReturn;
syncInterestById[tokenId]=interestRate;
if(gradualDivs){
require(secondsInTerm>=TERM_DURATIONS[2],"dividend bearing CBONDs must be at least 1 year duration");
totalQuarterlyCBONDS=totalQuarterlyCBONDS.add(1);
}
}
/*
Following two functions work immediately after all the Cbond variables except the interest rate have been set, will be inaccurate other times. To be used as part of Cbond creation.
*/
/*
Gets the amount of Sync for the given Cbond to return on maturity.
*/
function getCbondTotalReturn(uint256 tokenId,uint256 syncAmount,address liqAddr,uint256 duration,bool isDivs) public view returns(uint256 interestRate,uint256 totalReturn){
// This is an integer math translation of P*(1+I) where P is principle I is interest rate. The new, equivalent formula is P*(c+I*c)/c where c is a constant of amount PERCENTAGE_PRECISION.
interestRate=getCbondInterestRateNow(liqAddr, duration,getLuckyExtra(tokenId),isDivs);
totalReturn = syncAmount.mul(PERCENTAGE_PRECISION.add(interestRate)).div(PERCENTAGE_PRECISION);
}
/*
Gets the interest rate for a Cbond given its relevant properties.
*/
function getCbondInterestRateNow(
address liqAddr,
uint256 duration,
uint256 luckyExtra,
bool quarterly) public view returns(uint256){
return getCbondInterestRate(
duration,
liqTokenTotalsByDay[liqAddr][lastDayTokenSupplyUpdated[liqAddr]],
liqTokenTotalsByDay[liqAddr][getDay(block.timestamp)],
syncSupplyByDay[lastDaySyncSupplyUpdated],
syncSupplyByDay[getDay(block.timestamp)],
interestRateByDay[lastDaySyncSupplyUpdated],
luckyExtra,
quarterly);
}
/*
This returns the Cbond interest rate. Divide by PERCENTAGE_PRECISION to get the real rate.
*/
function getCbondInterestRate(
uint256 duration,
uint256 liqTotalLast,
uint256 liqTotalCurrent,
uint256 syncTotalLast,
uint256 syncTotalCurrent,
uint256 lastBaseInterestRate,
uint256 luckyExtra,
bool quarterly) public view returns(uint256){
uint256 liquidityPairIncentiveRate=getLiquidityPairIncentiveRate(liqTotalCurrent,liqTotalLast);
uint256 baseInterestRate=getBaseInterestRate(lastBaseInterestRate,syncTotalCurrent,syncTotalLast);
if(!quarterly){
return getDurationRate(duration,baseInterestRate.add(liquidityPairIncentiveRate).add(luckyExtra));
}
else{
uint numYears=duration.div(YEAR_LENGTH);
require(numYears>0,"invalid duration");//Quarterly Cbonds must have a duration 1 year or longer.
uint numQuarters=duration.div(QUARTER_LENGTH);
uint termModifier=RISK_FACTOR.mul(numYears.mul(4).sub(1));
//Interest rate is the sum of base interest rate, liquidity incentive rate, and risk/term based modifier. Because this is the Quarterly Cbond rate, we also divide by the number of quarters in the Cbond, to set the recorded rate to the amount withdrawable per quarter.
return baseInterestRate.add(liquidityPairIncentiveRate).add(luckyExtra).add(termModifier);
}
}
/*
This returns the Lucky Extra bonus of the given Cbond. This is based on whether the id of the Cbond ends in two or three 7's, and whether admins have disabled this feature.
*/
function getLuckyExtra(uint256 tokenId) public view returns(uint256){
if(luckyEnabled){
if(tokenId.mod(100)==77){
return LUCKY_EXTRAS[0];
}
if(tokenId.mod(1000)==777){
return LUCKY_EXTRAS[1];
}
}
return 0;
}
/*
New implementation of duration modifier. Approximation of intended formula.
*/
function getDurationRate(uint duration, uint baseInterestRate) public view returns(uint){
require(duration==TERM_DURATIONS[0] || duration==TERM_DURATIONS[1] || duration==TERM_DURATIONS[2] || duration==TERM_DURATIONS[3] || duration==TERM_DURATIONS[4],"Invalid CBOND term length provided");
if(duration==TERM_DURATIONS[0]){
return baseInterestRate;
}
if(duration==TERM_DURATIONS[1]){
uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR);
uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION);
return exponential.sub(PERCENTAGE_PRECISION);
}
if(duration==TERM_DURATIONS[2]){//1 year
uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(3));
uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION);
for (uint8 i=0;i<2;i++) {
exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION);
}
return exponential.sub(PERCENTAGE_PRECISION);
}
if(duration==TERM_DURATIONS[3]){//2 years
uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(7));
uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION);
for (uint8 i=0;i<6;i++) {
exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION);
}
return exponential.sub(PERCENTAGE_PRECISION);
}
if(duration==TERM_DURATIONS[4]){//3 years
uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(11));
uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION);
for (uint8 i=0;i<10;i++) {
exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION);
}
return exponential.sub(PERCENTAGE_PRECISION);
}
}
/*
Returns the liquidity pair incentive rate. To use, multiply by a value then divide result by PERCENTAGE_PRECISION
*/
function getLiquidityPairIncentiveRate(uint256 totalToday,uint256 totalYesterday) public view returns(uint256){
//instead of reverting due to division by zero, if tokens in this contract go to zero give the max bonus
if(totalToday==0){
return INCENTIVE_MAX_PERCENT;
}
return Math.min(INCENTIVE_MAX_PERCENT,INCENTIVE_MAX_PERCENT.mul(totalYesterday).div(totalToday));
}
/*
Returns the base interest rate, derived from the previous day interest rate, the current Sync total supply, and the previous day Sync total supply.
*/
function getBaseInterestRate(uint256 lastdayInterestRate,uint256 syncSupplyToday,uint256 syncSupplyLast) public pure returns(uint256){
return Math.min(MAXIMUM_BASE_INTEREST_RATE,Math.max(MINIMUM_BASE_INTEREST_RATE,lastdayInterestRate.mul(syncSupplyToday).div(syncSupplyLast)));
}
/*
Returns the interest rate a Cbond with the given parameters would end up with if it were created.
*/
function getCbondInterestRateIfUpdated(address liqAddr,uint256 duration,uint256 luckyExtra,bool quarterly) public view returns(uint256){
(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate)=getSuppliesIfUpdated(liqAddr);
return getCbondInterestRate(duration,lastTSupply,currentTSupply,lastSupply,currentSupply,lastInterestRate,luckyExtra,quarterly);
}
/*
Convenience function for frontend use which returns current and previous recorded Sync total supply, and tokens held for the provided token.
*/
function getSuppliesNow(address tokenAddr) public view returns(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate){
currentSupply=syncSupplyByDay[currentDaySyncSupplyUpdated];
lastSupply=syncSupplyByDay[lastDaySyncSupplyUpdated];
lastInterestRate=interestRateByDay[lastDaySyncSupplyUpdated];
currentTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]];
lastTSupply=liqTokenTotalsByDay[tokenAddr][lastDayTokenSupplyUpdated[tokenAddr]];
}
/*
Gets what the Sync and liquidity token current and last supplies would become, if updated now. Intended for frontend use.
*/
function getSuppliesIfUpdated(address tokenAddr) public view returns(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate){
uint256 day=getDay(block.timestamp);
if(liqTokenTotalsByDay[tokenAddr][getDay(block.timestamp)]==0){
currentTSupply=IERC20(tokenAddr).balanceOf(address(this));
lastTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]];
}
else{
currentTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]];
lastTSupply=liqTokenTotalsByDay[tokenAddr][lastDayTokenSupplyUpdated[tokenAddr]];
}
if(syncSupplyByDay[day]==0){
currentSupply=syncToken.totalSupply();
lastSupply=syncSupplyByDay[currentDaySyncSupplyUpdated];
//TODO: interest rate
lastInterestRate=interestRateByDay[currentDaySyncSupplyUpdated];
}
else{
currentSupply=syncSupplyByDay[currentDaySyncSupplyUpdated];
lastSupply=syncSupplyByDay[lastDaySyncSupplyUpdated];
lastInterestRate=interestRateByDay[lastDaySyncSupplyUpdated];
}
}
/*
Function for recording the Sync total supply and base interest rate by day. Records only at the first time it is called in a given day (see getDay).
*/
function recordSyncSupply() public{
if(syncSupplyByDay[getDay(block.timestamp)]==0){
uint256 day=getDay(block.timestamp);
syncSupplyByDay[day]=syncToken.totalSupply();
lastDaySyncSupplyUpdated=currentDaySyncSupplyUpdated;
currentDaySyncSupplyUpdated=day;
//interest rate
interestRateByDay[day]=getBaseInterestRate(interestRateByDay[lastDaySyncSupplyUpdated],syncSupplyByDay[day],syncSupplyByDay[lastDaySyncSupplyUpdated]);
}
}
/*
Records the current amount of the given token held by this contract for the current day. Like recordSyncSupply, only records the first time it is called in a day.
*/
function recordTokenSupply(address tokenAddr) private{
if(liqTokenTotalsByDay[tokenAddr][getDay(block.timestamp)]==0){
uint256 day=getDay(block.timestamp);
liqTokenTotalsByDay[tokenAddr][day]=IERC20(tokenAddr).balanceOf(address(this));
lastDayTokenSupplyUpdated[tokenAddr]=currentDayTokenSupplyUpdated[tokenAddr];
currentDayTokenSupplyUpdated[tokenAddr]=day;
}
}
/*
Gets the current day since the contract began. Starts at 1.
*/
function getDay(uint256 timestamp) public view returns(uint256){
return timestamp.sub(STARTING_TIME).div(24 hours).add(1);
}
/*
Gets the current day since the contract began, at the current block time.
*/
function getDayNow() public view returns(uint256){
return getDay(block.timestamp);
}
} | /TODO: add the rest of the variables, separate with appropriate url variable separators for ease of use | function putTogetherMetadataString(uint256 tokenId) public view returns(string memory){
string memory isDivs=gradualDivsById[tokenId]?"true":"false";
return string(abi.encodePacked("/?tokenId=",tokenId.toString(),"&lAddr=",lAddrById[tokenId].toString(),"&syncPrice=", syncPriceById[tokenId].toString(),"&syncAmount=",syncAmountById[tokenId].toString(),"&mPayout=",syncRewardedOnMaturity[tokenId].toString(),"&lPrice=",lTokenPriceById[tokenId].toString(),"&lAmount=",lTokenAmountById[tokenId].toString(),"&startTime=",timestampById[tokenId].toString(),"&isDivs=",isDivs,"&termLength=",termLengthById[tokenId].toString(),"&divsNow=",dividendsOf(tokenId).toString()));
}
| 7,280,277 |
./partial_match/1/0x19c5990E1A04ab4567B29d5822F55CDA44d53D4C/sources/StrategyUwuWeth.sol | Emergency functions call contract in current context throw if delegatecall failed | function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
function harvest() public virtual;
function execute(address _target, bytes memory _data) public payable returns (bytes memory response) {
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
revert(add(response, 0x20), size)
}
}
}
| 2,775,782 |
pragma solidity ^0.4.10;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
library DexLib {
using SafeMath for uint;
uint constant MAXORDER = 2**12;
uint constant MAXTOKEN = 2**7;
uint constant MAXBATCH = 2**7;
enum OrderType {Bid, Ask}
event SettledOrder(string tokenA, string tokenB, uint price, uint volume);
//order fee not implemented!!!
struct Order {
uint volume;
uint price;
address trader;
bytes32 nonce;
uint timestamp;
}
struct OrderBook {
uint numOrder;
Order[MAXORDER] orders;
}
struct Batch {
uint batchHead; //the actual head - 1
uint batchTail; //the actual tail
uint[MAXBATCH] timestamp;
OrderBook[MAXBATCH] bidBook;
OrderBook[MAXBATCH] askBook;
}
struct Token {
string symbolName;
address tokenAddr;
Batch[MAXTOKEN] batches;
}
struct NFToken {
string symbolName;
address tokenAddr;
mapping (uint => bool) existing;
mapping (uint => uint8) tradingToken;
mapping (uint => Batch) batches;
mapping (uint => address) owner;
}
struct Dex {
uint8 numToken;
uint8 numNFToken;
Token[MAXTOKEN] tokens;
NFToken[MAXTOKEN] nftokens;
mapping (string => uint8) tokenIndex;
mapping (string => uint8) nftokenIndex;
mapping (address => mapping (uint8 => uint)) balance;
mapping (address => mapping (uint8 => uint)) freeBal;
address admin;
uint lenPeriod;
uint staPeriod;
}
function initOrder(Order storage self, address trader, uint volume, uint price,
bytes32 nonce, uint timestamp) internal {
self.trader = trader;
self.volume = volume;
self.price = price;
self.nonce = nonce;
self.timestamp = timestamp;
}
function copyOrder(Order storage self, Order storage origin) internal{
initOrder(self, origin.trader, origin.volume, origin.price, origin.nonce, origin.timestamp);
}
function initBatch(Batch storage self) internal {
self.batchHead = 0;
self.batchTail = 0;
}
function initToken(Token storage self, address addr, string name) internal {
self.symbolName = name;
self.tokenAddr = addr;
for (uint i = 0; i < MAXTOKEN; i++) {
initBatch(self.batches[i]);
}
}
function initNFToken(NFToken storage self, address addr, string name) internal {
self.symbolName = name;
self.tokenAddr = addr;
}
function initDex (Dex storage self, address admin_, uint lenPeriod) internal {
self.admin = admin_;
self.lenPeriod = lenPeriod;
self.staPeriod = block.number;
self.numToken = 1;
initToken(self.tokens[self.numToken], 0, "ETH");
self.tokenIndex["ETH"] = self.numToken;
self.numNFToken = 0;
}
function updateBatchIndex(uint idx) public pure returns (uint) {
if (idx == MAXBATCH - 1) {
return 0;
} else {
return idx + 1;
}
}
function currentPeriod(Dex storage dex, uint cur) public view returns(uint) {
return ((cur - dex.staPeriod) / dex.lenPeriod) * dex.lenPeriod + dex.staPeriod;
}
function currentPeriod(uint period, uint sta, uint cur) public view returns (uint) {
return ((cur - sta) / period) * period + sta;
}
/* function updatePeriod(Dex storage self) public {
//Handle who is responsible for gas cost in this function!!!
if (self.curPeriod + self.lenPeriod <= block.number) {
self.curPeriod += self.lenPeriod;
for (uint i = 0; i < self.numToken; i++) {
for (uint j = 0; j < i; j++) {
self.tokens[i].batches[j].batchTail = updateBatchIndex(
self.tokens[i].batches[j].batchTail);
self.tokens[i].batches[j].timeTail += self.lenPeriod;
self.tokens[i].batches[j].bidBook[self.tokens[i].batches[j].batchTail].numOrder = 0;
self.tokens[i].batches[j].askBook[self.tokens[i].batches[j].batchTail].numOrder = 0;
}
}
}
}
*/
//event OrderNumber(string src, uint num);
function insertOrder(Batch storage self, uint timestamp, Order storage order,
OrderType t) internal {
if (self.batchHead == self.batchTail || self.timestamp[self.batchTail] < timestamp) {
self.batchTail = updateBatchIndex(self.batchTail);
self.timestamp[self.batchTail] = timestamp;
self.bidBook[self.batchTail].numOrder = 0;
self.askBook[self.batchTail].numOrder = 0;
}
if (t == OrderType.Bid) {
copyOrder(self.bidBook[self.batchTail].orders[self.bidBook[self.batchTail].numOrder],
order);
self.bidBook[self.batchTail].numOrder++;
//emit OrderNumber("inserOrder bid", self.bidBook[self.batchTail].numOrder);
} else {
copyOrder(self.askBook[self.batchTail].orders[self.askBook[self.batchTail].numOrder],
order);
self.askBook[self.batchTail].numOrder++;
//emit OrderNumber("insertOrder ask",self.bidBook[self.batchTail].numOrder);
}
}
//check whether priceA < priceB
function compareOrder(Order storage orderA, Order storage orderB)
public view returns(bool) {
return (orderA.price < orderB.price ||
(orderA.price == orderB.price && orderA.nonce < orderB.nonce));
}
//bids price in descending order, asks price in ascending order
function checkSortedBook(OrderBook storage self, uint[] sortedOrder, OrderType t)
public view returns(bool) {
if (self.numOrder != sortedOrder.length) return false;
for (uint i = 1; i < sortedOrder.length; i++) {
if (sortedOrder[i] == sortedOrder[i - 1]) return false;
if (t == OrderType.Bid) {
if (compareOrder(self.orders[sortedOrder[i - 1]],
self.orders[sortedOrder[i]])) return false;
} else {
if (compareOrder(self.orders[sortedOrder[i]],
self.orders[sortedOrder[i - 1]])) return false;
}
}
return true;
}
function checkSorting(Batch storage self, uint[] sortedBid, uint[] sortedAsk)
public view returns(bool) {
uint next = updateBatchIndex(self.batchHead);
return (checkSortedBook(self.bidBook[next], sortedBid, OrderType.Bid)
&& checkSortedBook(self.askBook[next], sortedAsk, OrderType.Ask));
}
function sortOrderBook(OrderBook storage self, OrderType t) internal returns(uint[]) {
//emit OrderNumber("sortOrderBook", self.numOrder);
uint[] memory sortedOrder = new uint[](MAXORDER);
for (uint i = 0; i < self.numOrder; i++) {
sortedOrder[i] = i;
}
//emit Sort("sortOrderBook:init",sortedOrder);
uint k;
for (i = 0; i < self.numOrder; i++) {
for (uint j = i; j < self.numOrder; j++) {
if (t == OrderType.Bid) {
if (compareOrder(self.orders[sortedOrder[i]], self.orders[sortedOrder[j]])) {
k = sortedOrder[i];
sortedOrder[i] = sortedOrder[j];
sortedOrder[j] = k;
}
} else {
if (!compareOrder(self.orders[sortedOrder[i]], self.orders[sortedOrder[j]])) {
k = sortedOrder[i];
sortedOrder[i] = sortedOrder[j];
sortedOrder[j] = k;
}
}
}
}
//emit Sort("sortOrderBook:after",sortedOrder);
return sortedOrder;
}
function min(uint a, uint b) public pure returns(uint) {
if (a < b) return a; else return b;
}
function firstPriceAuction(Dex storage dex, uint[] sortedBid, uint[] sortedAsk,
uint8 tokenA, uint8 tokenB) internal {
Batch storage self = dex.tokens[tokenA].batches[tokenB];
uint cur = updateBatchIndex(self.batchHead);
uint i = 0;
uint j = 0;
Order storage orderBid;
if (i < self.bidBook[cur].numOrder) orderBid = self.bidBook[cur].orders[sortedBid[i]];
Order storage orderAsk;
if (j < self.askBook[cur].numOrder) orderAsk = self.askBook[cur].orders[sortedAsk[j]];
for (; i < self.bidBook[cur].numOrder && j < self.askBook[cur].numOrder;) {
if (orderBid.price >= orderAsk.price) {
//how to set the settlement price when bid and ask prices are not equal???
uint price = (orderBid.price + orderAsk.price) / 2;
uint volume = min(orderBid.volume, orderAsk.volume);
//buy (volume) "tokenTo" with (volume * price) "tokenFrom" [tokenFrom][tokenTo]
dex.balance[orderBid.trader][tokenA] = dex.balance[orderBid.trader][tokenA].sub(volume.mul(price));
dex.balance[orderBid.trader][tokenB] = dex.balance[orderBid.trader][tokenB].add(volume);
dex.freeBal[orderBid.trader][tokenB] = dex.freeBal[orderBid.trader][tokenB].add(volume);
orderBid.volume -= volume;
if (orderBid.volume == 0) {
i++;
if (i < self.bidBook[cur].numOrder) orderBid = self.bidBook[cur].orders[sortedBid[i]];
}
//sell (volume) "tokenFrom" for (volume * price) "tokenTo" [tokenTo][tokenFrom]
dex.balance[orderAsk.trader][tokenA] = dex.balance[orderAsk.trader][tokenA].add(volume.mul(price));
dex.freeBal[orderAsk.trader][tokenA] = dex.freeBal[orderAsk.trader][tokenA].add(volume.mul(price));
dex.balance[orderAsk.trader][tokenB] = dex.balance[orderAsk.trader][tokenB].sub(volume);
orderAsk.volume -= volume;
if (orderAsk.volume == 0) {
j++;
if (j < self.askBook[cur].numOrder) orderAsk = self.askBook[cur].orders[sortedAsk[j]];
}
emit SettledOrder(dex.tokens[tokenA].symbolName, dex.tokens[tokenB].symbolName, price, volume);
} else {
break;
}
}
if (i < self.bidBook[cur].numOrder || j < self.askBook[cur].numOrder) {
if (cur == self.batchTail) {
self.batchTail = updateBatchIndex(self.batchTail);
self.timestamp[self.batchTail] = currentPeriod(dex, block.number);
self.bidBook[self.batchTail].numOrder = 0;
self.askBook[self.batchTail].numOrder = 0;
}
uint next = updateBatchIndex(cur);
for (; i < self.bidBook[cur].numOrder; i++) {
orderBid = self.bidBook[cur].orders[sortedBid[i]];
copyOrder(self.bidBook[next].orders[self.bidBook[next].numOrder], orderBid);
self.bidBook[next].numOrder++;
}
for (; j < self.askBook[cur].numOrder; j++) {
orderAsk = self.askBook[cur].orders[sortedAsk[j]];
copyOrder(self.askBook[next].orders[self.askBook[next].numOrder], orderAsk);
self.askBook[next].numOrder++;
}
}
self.batchHead = cur;
}
function firstPriceAuctionNFT(Dex storage dex, uint[] sortedBid, uint[] sortedAsk,
uint8 nft, uint tokenId) internal returns(uint) {
uint8 ft = dex.nftokens[nft].tradingToken[tokenId];
Batch storage self = dex.nftokens[nft].batches[tokenId];
uint cur = updateBatchIndex(self.batchHead);
if (self.bidBook[cur].numOrder > 0 && self.askBook[cur].numOrder > 0 &&
self.bidBook[cur].orders[sortedBid[0]].price >=
self.askBook[cur].orders[sortedAsk[0]].price) {
Order storage orderBid = self.bidBook[cur].orders[sortedBid[0]];
Order storage orderAsk = self.askBook[cur].orders[sortedAsk[0]];
//how to set the settlement price when bid and ask prices are not equal???
uint price = orderBid.price;
//buy 1 NFT with (price) FT [NFT][FT]
dex.balance[orderBid.trader][ft] = dex.balance[orderBid.trader][ft].sub(price);
dex.nftokens[nft].owner[tokenId] = orderBid.trader;
//sell 1 NFT for (price) FT [NFT][FT]
dex.balance[orderAsk.trader][ft] = dex.balance[orderAsk.trader][ft].add(price);
emit SettledOrder(dex.nftokens[nft].symbolName, dex.tokens[ft].symbolName, price, tokenId);
dex.nftokens[nft].tradingToken[tokenId] = 0;
initBatch(self);
return price;
} else {
if (0 < self.bidBook[cur].numOrder || 0 < self.askBook[cur].numOrder) {
if (cur == self.batchTail) {
self.batchTail = updateBatchIndex(self.batchTail);
self.timestamp[self.batchTail] = currentPeriod(dex.lenPeriod, self.timestamp[cur], block.number);
self.bidBook[self.batchTail].numOrder = 0;
self.askBook[self.batchTail].numOrder = 0;
}
uint next = updateBatchIndex(cur);
uint i;
for (i = 0; i < self.bidBook[cur].numOrder; i++) {
orderBid = self.bidBook[cur].orders[sortedBid[i]];
copyOrder(self.bidBook[next].orders[self.bidBook[next].numOrder], orderBid);
self.bidBook[next].numOrder++;
}
for (i = 0; i < self.askBook[cur].numOrder; i++) {
orderAsk = self.askBook[cur].orders[sortedAsk[i]];
copyOrder(self.askBook[next].orders[self.askBook[next].numOrder], orderAsk);
self.askBook[next].numOrder++;
}
}
self.batchHead = cur;
return 0;
}
}
function settle(Dex storage dex, uint[] sortedBid, uint[] sortedAsk,
uint8 tokenA, uint8 tokenB) internal {
Batch storage self = dex.tokens[tokenA].batches[tokenB];
require(self.batchHead != self.batchTail);
require(self.timestamp[updateBatchIndex(self.batchHead)] + dex.lenPeriod <= block.number);
require(checkSorting(self, sortedBid, sortedAsk));
firstPriceAuction(dex, sortedBid, sortedAsk, tokenA, tokenB);
}
function settleNFT(Dex storage dex, uint[] sortedBid, uint[] sortedAsk,
uint8 nft, uint tokenId) internal {
Batch storage self = dex.nftokens[nft].batches[tokenId];
require(self.batchHead != self.batchTail);
require(self.timestamp[updateBatchIndex(self.batchHead)] + dex.lenPeriod <= block.number);
require(checkSorting(self, sortedBid, sortedAsk));
firstPriceAuctionNFT(dex, sortedBid, sortedAsk, nft, tokenId);
}
//event Sort(string src, uint[] arr);
event Blocknumber(uint a, uint period, uint blocknumber);
function settleNFT(Dex storage dex, uint8 nft, uint tokenId) internal returns(uint) {
Batch storage self = dex.nftokens[nft].batches[tokenId];
require(self.batchHead != self.batchTail);
require(self.timestamp[updateBatchIndex(self.batchHead)] + dex.lenPeriod <= block.number);
emit Blocknumber(self.timestamp[updateBatchIndex(self.batchHead)], dex.lenPeriod, block.number);
uint next = updateBatchIndex(self.batchHead);
uint[] memory sortedBid = sortOrderBook(self.bidBook[next], OrderType.Bid);
//emit Sort("settleNFT", sortedBid);
uint[] memory sortedAsk = sortOrderBook(self.askBook[next], OrderType.Ask);
return firstPriceAuctionNFT(dex, sortedBid, sortedAsk, nft, tokenId);
}
}
| how to set the settlement price when bid and ask prices are not equal???buy (volume) "tokenTo" with (volume price) "tokenFrom" [tokenFrom][tokenTo] | function firstPriceAuction(Dex storage dex, uint[] sortedBid, uint[] sortedAsk,
for (; i < self.bidBook[cur].numOrder && j < self.askBook[cur].numOrder;) {
if (orderBid.price >= orderAsk.price) {
uint price = (orderBid.price + orderAsk.price) / 2;
uint volume = min(orderBid.volume, orderAsk.volume);
dex.balance[orderBid.trader][tokenA] = dex.balance[orderBid.trader][tokenA].sub(volume.mul(price));
dex.balance[orderBid.trader][tokenB] = dex.balance[orderBid.trader][tokenB].add(volume);
dex.freeBal[orderBid.trader][tokenB] = dex.freeBal[orderBid.trader][tokenB].add(volume);
orderBid.volume -= volume;
if (orderBid.volume == 0) {
i++;
if (i < self.bidBook[cur].numOrder) orderBid = self.bidBook[cur].orders[sortedBid[i]];
}
dex.freeBal[orderAsk.trader][tokenA] = dex.freeBal[orderAsk.trader][tokenA].add(volume.mul(price));
dex.balance[orderAsk.trader][tokenB] = dex.balance[orderAsk.trader][tokenB].sub(volume);
orderAsk.volume -= volume;
if (orderAsk.volume == 0) {
j++;
if (j < self.askBook[cur].numOrder) orderAsk = self.askBook[cur].orders[sortedAsk[j]];
}
emit SettledOrder(dex.tokens[tokenA].symbolName, dex.tokens[tokenB].symbolName, price, volume);
break;
}
}
| 6,352,427 |
./full_match/80001/0xa64BE9813EA7B7B0995B51F919a25235006B99cF/sources/sfds.sol | See {IERC721Enumerable-tokenByIndex}./ | function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Tradeable: global index out of bounds");
return _allTokens[index];
}
| 9,492,732 |
./full_match/1/0x60Fa954e22c42F52E8C815a9476f339BD38AEEf7/sources/contracts/core/defi/three-x/storage/AbstractBatchStorage.sol | todo `clients` ultimately may withdraw tokens for a batch they create at anytime by calling withdrawSourceTokenFromBatch. tokens may be transfered out of this contract if the given recipient is a registered client or if the client has granted an allowance to a recipient to receive tokens. this means that in order to trust this contract, you must look at the clients because they can give themselves infinite allowance as a recipient of a target token from this contract. simply put, a rogue contract may infinite approve everything held by the contract and potentially send to itself. any new client to this contract must be reviewed to ensure it does not make a claim or withdrawal for an address for which it should not. thought was given to designing this in a way to offer permissionless batch logic for any client, but greater attention would need to be given to scopes and boundaries. consider apodoting eip-1155 / eip-4626 standard interfaces for greater interoperability/ | function _transfer(
IERC20 token,
address owner,
address recipient,
bytes32 batchId,
uint256 amount
) internal {
if (recipient != address(0)) {
Batch memory batch = batches[batchId];
uint256 allowance = allowances[msg.sender][recipient][batchId][address(token)];
bool hasAllowance = allowance >= amount;
require(
recipient == owner || hasAllowance || recipient == batch.owner || delegates[batch.owner][recipient],
"won't send"
);
if (hasAllowance && allowance != 0) {
allowances[msg.sender][recipient][batchId][address(token)] -= amount;
}
token.safeTransfer(recipient, amount);
}
}
| 4,889,323 |
./partial_match/3/0x25E2e5D8EcC4fE46a9505079Ed29266779dC7D6f/sources/HoprChannels.sol | redeem ticket preImage bytes32 the value that once hashed produces recipients hashedSecret hashedSecretASecretB bytes32 hash of secretA concatenated with secretB amount uint256 amount 'msg.sender' will receive winProb bytes32 win probability r bytes32 s bytes32 v uint8/ @TODO Uncomment next line to enable salted hash accounts[msg.sender].hashedSecret == bytes27(keccak256(abi.encodePacked("HOPRnet", msg.sender, bytes27(preImage)))), | function redeemTicket(
bytes32 preImage,
bytes32 hashedSecretASecretB,
uint256 amount,
bytes32 winProb,
address counterparty,
bytes32 r,
bytes32 s,
uint8 v
) external {
require(amount > 0, "HoprChannels: amount must be strictly greater than zero");
require(amount < (1 << 96), "HoprChannels: Invalid amount");
require(
accounts[msg.sender].hashedSecret == bytes27(keccak256(abi.encodePacked(bytes27(preImage)))),
"HoprChannels: Given value is not a pre-image of the stored on-chain secret"
);
(address partyA, , Channel storage channel, ChannelStatus status) = getChannel(
msg.sender,
counterparty
);
bytes32 challenge = keccak256(abi.encodePacked(hashedSecretASecretB));
bytes32 hashedTicket = ECDSA.toEthSignedMessageHash(
"109",
abi.encodePacked(
msg.sender,
challenge,
uint24(accounts[msg.sender].counter),
uint96(amount),
winProb,
uint24(getChannelIteration(channel))
)
);
require(ECDSA.recover(hashedTicket, r, s, v) == counterparty, "HashedTicket signer does not match our counterparty");
require(channel.stateCounter != uint24(0), "HoprChannels: Channel does not exist");
require(!redeemedTickets[hashedTicket], "Ticket must not be used twice");
bytes32 luck = keccak256(abi.encodePacked(hashedTicket, bytes27(preImage), hashedSecretASecretB));
require(uint256(luck) <= uint256(winProb), "HoprChannels: ticket must be a win");
require(
status == ChannelStatus.OPEN || status == ChannelStatus.PENDING,
"HoprChannels: channel must be 'OPEN' or 'PENDING'"
);
accounts[msg.sender].hashedSecret = bytes27(preImage);
redeemedTickets[hashedTicket] = true;
if (msg.sender == partyA) {
require(channel.partyABalance + amount < (1 << 96), "HoprChannels: Invalid amount");
channel.partyABalance += uint96(amount);
require(channel.partyABalance >= amount, "HoprChannels: Invalid amount");
channel.partyABalance -= uint96(amount);
}
require(
channel.partyABalance <= channel.deposit,
"HoprChannels: partyABalance must be strictly smaller than deposit balance"
);
}
| 5,147,860 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
library Internal_Merkle_Library_Sorted_Hash {
// Hashes a and b in the order they are passed
function hash_node(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
hash := keccak256(0x00, 0x40)
}
}
// Hashes a and b in sorted order
function hash_pair(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
hash = a < b ? hash_node(a, b) : hash_node(b, a);
}
// Counts number of set bits (1's) in 32-bit unsigned integer
function bit_count_32(uint32 n) internal pure returns (uint32) {
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
// Round 32-bit unsigned integer up to the nearest power of 2
function round_up_to_power_of_2(uint32 n) internal pure returns (uint32) {
if (bit_count_32(n) == 1) return n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
// Get the Element Merkle Root for a tree with just a single bytes element in calldata
function get_root_from_one_c(bytes calldata element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes element in memory
function get_root_from_one_m(bytes memory element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes32 element in calldata
function get_root_from_one(bytes32 element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get nodes (parent of leafs) from bytes elements in calldata
function get_nodes_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes elements in memory
function get_nodes_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in calldata
function get_nodes_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in memory
function get_nodes_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get the Element Merkle Root given nodes (parent of leafs)
function get_root_from_nodes(bytes32[] memory nodes) internal pure returns (bytes32) {
uint256 node_count = nodes.length;
uint256 write_index;
uint256 left_index;
while (node_count > 1) {
left_index = write_index << 1;
if (left_index == node_count - 1) {
nodes[write_index] = nodes[left_index];
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
if (left_index >= node_count) {
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
nodes[write_index++] = hash_pair(nodes[left_index], nodes[left_index + 1]);
}
return nodes[0];
}
// Get the Element Merkle Root for a tree with several bytes elements in calldata
function get_root_from_many_c(bytes[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes elements in memory
function get_root_from_many_m(bytes[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in calldata
function get_root_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in memory
function get_root_from_many_m(bytes32[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// get_root_from_size_proof cannot be implemented with sorted hashed pairs
// Get the original Element Merkle Root, given an index, a leaf, and a Single Proof
function get_root_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
leaf = hash_pair(proof[proof_index], leaf);
proof_index -= 1;
}
index >>= 1;
upper_bound >>= 1;
}
return leaf;
}
// Get the original Element Merkle Root, given an index, a bytes element in calldata, and a Single Proof
function get_root_from_single_proof_c(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes element in memory, and a Single Proof
function get_root_from_single_proof_m(
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes32 element, and a Single Proof
function get_root_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a leaf, an update leaf, and a Single Proof
function get_roots_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 scratch, bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if ((index != upper_bound) || (index & 1 == 1)) {
scratch = proof[proof_index];
proof_index -= 1;
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
}
index >>= 1;
upper_bound >>= 1;
}
return (leaf, update_leaf);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_roots_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_roots_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_roots_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// get_indices_from_multi_proof cannot be implemented with sorted hashed pairs
// Get leafs from bytes elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes32[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes32[] memory elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original Element Merkle Root, given leafs and an Existence Multi Proof
function get_root_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 right)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) return leafs[(write_index == 0 ? leaf_count : write_index) - 1];
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
right = (flags & bit_check == bit_check) ? leafs[read_index++] : proof[proof_index++];
read_index %= leaf_count;
leafs[write_index] = hash_pair(right, leafs[read_index]);
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root, given bytes elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes32[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original and updated Element Merkle Root, given leafs, update leafs, and an Existence Multi Proof
function get_roots_from_leafs_and_multi_proof_update(
bytes32[] memory leafs,
bytes32[] memory update_leafs,
bytes32[] calldata proof
) internal pure returns (bytes32 flags, bytes32 skips) {
uint256 leaf_count = update_leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
flags = proof[1];
skips = proof[2];
bytes32 scratch;
uint256 scratch_2;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
return (leafs[read_index], update_leafs[read_index]);
}
leafs[write_index] = leafs[read_index];
update_leafs[write_index] = update_leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (flags & bit_check == bit_check) {
scratch_2 = (read_index + 1) % leaf_count;
leafs[write_index] = hash_pair(leafs[read_index], leafs[scratch_2]);
update_leafs[write_index] = hash_pair(update_leafs[read_index], update_leafs[scratch_2]);
read_index += 2;
} else {
scratch = proof[proof_index++];
leafs[write_index] = hash_pair(scratch, leafs[read_index]);
update_leafs[write_index] = hash_pair(scratch, update_leafs[read_index]);
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original Element Merkle Root, given an Append Proof
function get_root_from_append_proof(bytes32[] calldata proof) internal pure returns (bytes32 hash) {
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
while (proof_index > 1) {
proof_index -= 1;
hash = hash_pair(proof[proof_index], hash);
}
}
// Get the original and updated Element Merkle Root, given append leaf and an Append Proof
function get_roots_from_leaf_and_append_proof_single_append(bytes32 append_leaf, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32 scratch)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
append_leaf = hash_pair(hash, append_leaf);
while (proof_index > 1) {
proof_index -= 1;
scratch = proof[proof_index];
append_leaf = hash_pair(scratch, append_leaf);
hash = hash_pair(scratch, hash);
}
return (hash, append_leaf);
}
// Get the original and updated Element Merkle Root, given a bytes append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes append element in memory and an Append Proof
function get_roots_from_append_proof_single_append_m(bytes memory append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes32 append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append(bytes32 append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get leafs from bytes elements in calldata
function get_leafs_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes elements in memory
function get_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in calldata
function get_leafs_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in memory
function get_leafs_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get the original and updated Element Merkle Root, given append leafs and an Append Proof
function get_roots_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = bit_count_32(uint32(offset));
hash = proof[proof_index];
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
proof_index -= 1;
read_index += 1;
if (proof_index > 0) {
hash = hash_pair(proof[proof_index], hash);
}
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index]);
read_index += 1;
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return (hash, append_leafs[0]);
}
// Get the original and updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given an append leaf and an Append Proof
function get_new_root_from_leafs_and_append_proof_single_append(bytes32 append_leaf, bytes32[] memory proof)
internal
pure
returns (bytes32 append_hash)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
append_hash = hash_pair(proof[proof_index], append_leaf);
while (proof_index > 1) {
proof_index -= 1;
append_hash = hash_pair(proof[proof_index], append_hash);
}
}
// Get the updated Element Merkle Root, given a bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_single_append_m(bytes memory append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append(bytes32 append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given append leafs and an Append Proof
function get_new_root_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = proof.length - 1;
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
read_index += 1;
proof_index -= 1;
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index++]);
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return append_leafs[0];
}
// Get the updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, an append leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes element in calldata, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes32 element, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a leaf, an update leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = update_leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = update_leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_append_proof_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_append_proof_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_append_proof_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Hashes leaf at read index and next index (circular) to write index
function hash_within_leafs(
bytes32[] memory leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
leafs[write_index] = hash_pair(leafs[read_index], leafs[(read_index + 1) % leaf_count]);
}
// Hashes value with leaf at read index to write index
function hash_with_leafs(
bytes32[] memory leafs,
bytes32 value,
uint256 write_index,
uint256 read_index
) internal pure {
leafs[write_index] = hash_pair(value, leafs[read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = uint256(bit_count_32(uint32(append_node_index))) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
uint256 read_index_of_append_node;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = flags;
}
return (append_hash, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = leafs[read_index]; // TODO scratch this leafs[read_index] above
append_proof[append_proof_index] = leafs[read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// reuse read_index_of_append_node as temporary scratch variable
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = leafs[read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_leafs(leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_leafs(leafs, proof[proof_index], write_index, read_index);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof, given bytes elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given bytes32 elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Copy leaf and update leaf at read indices and to write indices
function copy_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
}
// Hashes leaf and update leaf at read indices and next indices (circular) to write indices
function hash_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
uint256 scratch = (read_index + 1) % leaf_count;
combined_leafs[write_index] = hash_pair(combined_leafs[read_index], combined_leafs[scratch]);
combined_leafs[leaf_count + write_index] = hash_pair(
combined_leafs[leaf_count + read_index],
combined_leafs[leaf_count + scratch]
);
}
// Hashes value with leaf and update leaf at read indices to write indices
function hash_with_combined_leafs(
bytes32[] memory combined_leafs,
bytes32 value,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = hash_pair(value, combined_leafs[read_index]);
combined_leafs[leaf_count + write_index] = hash_pair(value, combined_leafs[leaf_count + read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given combined leafs and update leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof_update(bytes32[] memory combined_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = combined_leafs.length >> 1;
uint256 read_index;
uint256 write_index;
uint256 read_index_of_append_node;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 flags = proof[1];
bytes32 skips = proof[2];
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = combined_leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = combined_leafs[leaf_count + read_index];
}
return (flags, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = combined_leafs[read_index];
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// use read_index_of_append_node as temporary scratch
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(combined_leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_combined_leafs(combined_leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_combined_leafs(combined_leafs, proof[proof_index], write_index, read_index, leaf_count);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_c(index, element, proof)) == root;
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_m(
bytes32 root,
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_m(index, element, proof)) == root;
}
// INTERFACE: Check if bytes32 element exists at index, given a root and a Single Proof
function element_exists(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof(index, element, proof)) == root;
}
// INTERFACE: Check if bytes elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes32[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// get_indices cannot be implemented with sorted hashed pairs
// verify_size_with_proof cannot be implemented with sorted hashed pairs
// INTERFACE: Check tree size, given a the Element Merkle Root
function verify_size(
bytes32 root,
uint256 size,
bytes32 element_root
) internal pure returns (bool) {
if (root == bytes32(0) && size == 0) return true;
return hash_node(bytes32(size), element_root) == root;
}
// INTERFACE: Try to update a bytes element in calldata, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes element in memory, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes32 element, given a root, and index, an bytes32 element, and a Single Proof
function try_update_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root and an Append Proof
function try_append_one_c(
bytes32 root,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_c(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_c(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root and an Append Proof
function try_append_one_m(
bytes32 root,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_m(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_m(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root and an Append Proof
function try_append_one(
bytes32 root,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, an index, a bytes32 element, and a Single Proof
function try_append_one_using_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_one_using_many(
bytes32 root,
bytes32[] calldata elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append a bytes element in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append a bytes element in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes32 element and append a bytes32 element,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append bytes elements in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append bytes elements in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in calldata,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in memory,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append a bytes element in calldata,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append a bytes element in memory,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append bytes elements in calldata,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append bytes elements in memory,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append bytes32 elements in calldata,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append bytes32 elements in memory,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Create a tree and return the root, given a bytes element in calldata
function create_from_one_c(bytes calldata element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_c(element));
}
// INTERFACE: Create a tree and return the root, given a bytes element in memory
function create_from_one_m(bytes memory element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_m(element));
}
// INTERFACE: Create a tree and return the root, given a bytes32 element
function create_from_one(bytes32 element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one(element));
}
// INTERFACE: Create a tree and return the root, given bytes elements in calldata
function create_from_many_c(bytes[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes elements in memory
function create_from_many_m(bytes[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in calldata
function create_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in memory
function create_from_many_m(bytes32[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
}
| Get the original Element Merkle Root and derive Append Proof, given an index, a leaf, an update leaf, and a Single Proof | function get_append_proof_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
append_proof_index -= 1;
append_proof[append_proof_index] = update_leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = update_leaf;
}
}
| 12,859,710 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Signature.sol";
contract TGE is Ownable, Signature {
using SafeERC20 for IERC20;
/** @dev Terms and conditions as a keccak256 hash */
string public constant termsAndConditions =
"By signing this message I agree to the $FOREX TOKEN - TERMS AND CONDITIONS identified by the hash: 0x1b42a1c6369d3efbf3b65d757e3f5e804bc26935b45dda1eaf0d90ef297289b4";
/** @dev ERC-191 encoded Terms and Conditions for signature validation */
bytes32 private constant termsAndConditionsERC191 =
keccak256(
abi.encodePacked(
bytes1(0x19),
bytes1("E"),
bytes("thereum Signed Message:\n165"),
abi.encodePacked(termsAndConditions)
)
);
/** @dev Error message for claiming before allowed period */
string private constant notClaimable = "Funds not yet claimable";
/** @dev The amount of FOREX to be generated */
uint256 public constant forexAmount = 20_760_000 ether;
/** @dev The address of this contract's deployed instance */
address private immutable self;
/** @dev Canonical FOREX token address */
address public immutable FOREX;
/** @dev Per-user deposit cap */
uint256 public immutable userCap;
/** @dev Minimum token price in ETH (soft cap parameter) */
uint256 public minTokenPrice;
/** @dev Maximum token price in ETH (if hard cap is met) */
uint256 public maxTokenPrice;
/** @dev Generation duration (seconds) */
uint256 public immutable generationDuration;
/** @dev Start date for the generation; when ETH deposits are accepted */
uint256 public immutable generationStartDate;
/** @dev Maximum deposit cap in ETH from which new deposits are ignored */
uint256 public depositCap;
/** @dev Date from when FOREX claiming is allowed */
uint256 public claimDate;
/** @dev Amount of ETH deposited during the TGE */
uint256 public ethDeposited;
/** @dev Mapping of (depositor => eth amount) for the TGE period */
mapping(address => uint256) private deposits;
/** @dev Mapping of (depositor => T&Cs signature status) */
mapping(address => bool) public signedTermsAndConditions;
/** @dev Mapping of (depositor => claimed eth) */
mapping(address => bool) private claimedEth;
/** @dev Mapping of (depositor => claimed forex) */
mapping(address => bool) private claimedForex;
/** @dev The total ETH deposited under a referral address */
mapping(address => uint256) public referrerDeposits;
/** @dev Number of depositors */
uint256 public depositorCount;
/** @dev Whether leftover FOREX tokens were withdrawn by owner
(only possible if FOREX did not reach the max price) */
bool private withdrawnRemainingForex;
/** @dev Whether the TGE was aborted by the owner */
bool private aborted;
/** @dev ETH withdrawn by owner */
uint256 public ethWithdrawnByOwner;
modifier notAborted() {
require(!aborted, "TGE aborted");
_;
}
constructor(
address _FOREX,
uint256 _userCap,
uint256 _depositCap,
uint256 _minTokenPrice,
uint256 _maxTokenPrice,
uint256 _generationDuration,
uint256 _generationStartDate
) {
require(_generationDuration > 0, "Duration must be > 0");
require(
_generationStartDate > block.timestamp,
"Start date must be in the future"
);
self = address(this);
FOREX = _FOREX;
userCap = _userCap;
depositCap = _depositCap;
minTokenPrice = _minTokenPrice;
maxTokenPrice = _maxTokenPrice;
generationDuration = _generationDuration;
generationStartDate = _generationStartDate;
}
/**
* @dev Deny direct ETH transfers.
*/
receive() external payable {
revert("Must call deposit to participate");
}
/**
* @dev Validates a signature for the hashed terms & conditions message.
* The T&Cs hash is converted to an ERC-191 message before verifying.
* @param signature The signature to validate.
*/
function signTermsAndConditions(bytes memory signature) public {
if (signedTermsAndConditions[msg.sender]) return;
address signer = getSignatureAddress(
termsAndConditionsERC191,
signature
);
require(signer == msg.sender, "Invalid signature");
signedTermsAndConditions[msg.sender] = true;
}
/**
* @dev Allow incoming ETH transfers during the TGE period.
*/
function deposit(address referrer, bytes memory signature)
external
payable
notAborted
{
// Sign T&Cs if the signature is not empty.
// User must pass a valid signature before the first deposit.
if (signature.length != 0) signTermsAndConditions(signature);
// Assert that the user can deposit.
require(signedTermsAndConditions[msg.sender], "Must sign T&Cs");
require(hasTgeBeenStarted(), "TGE has not started yet");
require(!hasTgeEnded(), "TGE has finished");
uint256 currentDeposit = deposits[msg.sender];
// Revert if the user cap or TGE cap has already been met.
require(currentDeposit < userCap, "User cap met");
require(ethDeposited < depositCap, "TGE deposit cap met");
// Assert that the deposit amount is greater than zero.
uint256 deposit = msg.value;
assert(deposit > 0);
// Increase the depositorCount if first deposit by user.
if (currentDeposit == 0) depositorCount++;
if (currentDeposit + deposit > userCap) {
// Ensure deposit over user cap is returned.
safeSendEth(msg.sender, currentDeposit + deposit - userCap);
// Adjust user deposit.
deposit = userCap - currentDeposit;
} else if (ethDeposited + deposit > depositCap) {
// Ensure deposit over TGE cap is returned.
safeSendEth(msg.sender, ethDeposited + deposit - depositCap);
// Adjust user deposit.
deposit -= ethDeposited + deposit - depositCap;
}
// Only contribute to referrals if the hard cap hasn't been met yet.
uint256 hardCap = ethHardCap();
if (ethDeposited < hardCap) {
uint256 referralDepositAmount = deposit;
// Subtract surplus from hard cap if any.
if (ethDeposited + deposit > hardCap)
referralDepositAmount -= ethDeposited + deposit - hardCap;
referrerDeposits[referrer] += referralDepositAmount;
}
// Increase deposit variables.
ethDeposited += deposit;
deposits[msg.sender] += deposit;
}
/**
* @dev Claim depositor funds (FOREX and ETH) once the TGE has closed.
This may be called right after TGE closing for withdrawing surplus
ETH (if FOREX reached max price/hard cap) or once (again when) the
claim period starts for claiming both FOREX along with any surplus.
*/
function claim() external notAborted {
require(hasTgeEnded(), notClaimable);
(uint256 forex, uint256 forexReferred, uint256 eth) = balanceOf(
msg.sender
);
// Revert here if there's no ETH to withdraw as the FOREX claiming
// period may not have yet started.
require(eth > 0 || isTgeClaimable(), notClaimable);
forex += forexReferred;
// Claim forex only if the claimable period has started.
if (isTgeClaimable() && forex > 0) claimForex(forex);
// Claim ETH hardcap surplus if available.
if (eth > 0) claimEthSurplus(eth);
}
/**
* @dev Claims ETH for user.
* @param eth The amount of ETH to claim.
*/
function claimEthSurplus(uint256 eth) private {
if (claimedEth[msg.sender]) return;
claimedEth[msg.sender] = true;
if (eth > 0) safeSendEth(msg.sender, eth);
}
/**
* @dev Claims FOREX for user.
* @param forex The amount of FOREX to claim.
*/
function claimForex(uint256 forex) private {
if (claimedForex[msg.sender]) return;
claimedForex[msg.sender] = true;
IERC20(FOREX).safeTransfer(msg.sender, forex);
}
/**
* @dev Withdraws leftover forex in case the hard cap is not met during TGE.
*/
function withdrawRemainingForex(address recipient) external onlyOwner {
assert(!withdrawnRemainingForex);
// Revert if the TGE has not ended.
require(hasTgeEnded(), "TGE has not finished");
(uint256 forexClaimable, ) = getClaimableData();
uint256 remainingForex = forexAmount - forexClaimable;
withdrawnRemainingForex = true;
// Add address zero (null) referrals to withdrawal.
remainingForex += getReferralForexAmount(address(0));
if (remainingForex == 0) return;
IERC20(FOREX).safeTransfer(recipient, remainingForex);
}
/**
* @dev Returns an account's balance of claimable forex, referral forex,
and ETH.
* @param account The account to fetch the claimable balance for.
*/
function balanceOf(address account)
public
view
returns (
uint256 forex,
uint256 forexReferred,
uint256 eth
)
{
if (!hasTgeEnded()) return (0, 0, 0);
(uint256 forexClaimable, uint256 ethClaimable) = getClaimableData();
uint256 share = shareOf(account);
eth = claimedEth[account] ? 0 : (ethClaimable * share) / (1 ether);
if (claimedForex[account]) {
forex = 0;
forexReferred = 0;
} else {
forex = (forexClaimable * share) / (1 ether);
// Forex earned through referrals is 5% of the referred deposits
// in FOREX.
forexReferred = getReferralForexAmount(account);
}
}
/**
* @dev Returns an account's share over the TGE deposits.
* @param account The account to fetch the share for.
* @return Share value as an 18 decimal ratio. 1 ether = 100%.
*/
function shareOf(address account) public view returns (uint256) {
if (ethDeposited == 0) return 0;
return (deposits[account] * (1 ether)) / ethDeposited;
}
/**
* @dev Returns the ETH deposited by an address.
* @param depositor The depositor address.
*/
function getDeposit(address depositor) external view returns (uint256) {
return deposits[depositor];
}
/**
* @dev Whether the TGE already started. It could be closed even if
this function returns true.
*/
function hasTgeBeenStarted() private view returns (bool) {
return block.timestamp >= generationStartDate;
}
/**
* @dev Whether the TGE has ended and is closed for new deposits.
*/
function hasTgeEnded() private view returns (bool) {
return block.timestamp > generationStartDate + generationDuration;
}
/**
* @dev Whether the TGE funds can be claimed.
*/
function isTgeClaimable() private view returns (bool) {
return claimDate != 0 && block.timestamp >= claimDate;
}
/**
* @dev The amount of ETH required to generate all supply at max price.
*/
function ethHardCap() private view returns (uint256) {
return (forexAmount * maxTokenPrice) / (1 ether);
}
/**
* @dev Returns the forex price as established by the deposit amount.
* The formula for the price is the following:
* minPrice + ([maxPrice - minPrice] * min(deposit, maxDeposit)/maxDeposit)
* Where maxDeposit = ethHardCap()
*/
function forexPrice() public view returns (uint256) {
uint256 hardCap = ethHardCap();
uint256 depositTowardsHardCap = ethDeposited > hardCap
? hardCap
: ethDeposited;
uint256 priceRange = maxTokenPrice - minTokenPrice;
uint256 priceDelta = (priceRange * depositTowardsHardCap) / hardCap;
return minTokenPrice + priceDelta;
}
/**
* @dev Returns TGE data to be used for claims once the TGE closes.
*/
function getClaimableData()
private
view
returns (uint256 forexClaimable, uint256 ethClaimable)
{
assert(hasTgeEnded());
uint256 forexPrice = forexPrice();
uint256 hardCap = ethHardCap();
// ETH is only claimable if the deposits exceeded the hard cap.
ethClaimable = ethDeposited > hardCap ? ethDeposited - hardCap : 0;
// Forex is claimable up to the maximum supply -- when deposits match
// the hard cap amount.
forexClaimable =
((ethDeposited - ethClaimable) * (1 ether)) /
forexPrice;
}
/**
* @dev Returns the amount of FOREX earned by a referrer.
* @param referrer The referrer's address.
*/
function getReferralForexAmount(address referrer)
private
view
returns (uint256)
{
// Referral claims are disabled.
return 0;
}
/**
* @dev Aborts the TGE, stopping new deposits and withdrawing all funds
* for the owner.
* The only use case for this function is in the
* event of an emergency.
*/
function emergencyAbort() external onlyOwner {
assert(!aborted);
aborted = true;
emergencyWithdrawAllFunds();
}
/**
* @dev Withdraws all contract funds for the owner.
* The only use case for this function is in the
* event of an emergency.
*/
function emergencyWithdrawAllFunds() public onlyOwner {
// Transfer ETH.
uint256 balance = self.balance;
if (balance > 0) safeSendEth(msg.sender, balance);
// Transfer FOREX.
IERC20 forex = IERC20(FOREX);
balance = forex.balanceOf(self);
if (balance > 0) forex.transfer(msg.sender, balance);
}
/**
* @dev Withdraws all ETH funds for the owner.
* This function may be called at any time, as it correctly
* withdraws only the correct contribution amount, ignoring
* the ETH amount to be refunded if the deposits exceed
* the hard cap.
*/
function collectContributions() public onlyOwner {
uint256 hardCap = ethHardCap();
require(
ethWithdrawnByOwner < hardCap,
"Cannot withdraw more than hard cap amount"
);
uint256 amount = self.balance;
if (amount + ethWithdrawnByOwner > hardCap)
amount = hardCap - ethWithdrawnByOwner;
ethWithdrawnByOwner += amount;
require(amount > 0, "Nothing available for withdrawal");
safeSendEth(msg.sender, amount);
}
/**
* @dev Enables FOREX claiming from the next block.
* Requires the TGE to have been closed.
*/
function enableForexClaims() external onlyOwner {
assert(hasTgeEnded() && !isTgeClaimable());
claimDate = block.timestamp + 1;
}
/**
* @dev Sets the minimum and maximum token prices before the TGE starts.
* Also sets the deposit cap.
* @param min The minimum token price in ETH.
* @param max The maximum token price in ETH.
* @param _depositCap The ETH deposit cap.
*/
function setMinMaxForexPrices(
uint256 min,
uint256 max,
uint256 _depositCap
) external onlyOwner {
assert(!hasTgeBeenStarted());
require(max > min && _depositCap > max, "Invalid values");
minTokenPrice = min;
maxTokenPrice = max;
depositCap = _depositCap;
}
/**
* @dev Sends ETH and reverts if the transfer fails.
* @param recipient The transfer recipient.
* @param amount The transfer amount.
*/
function safeSendEth(address recipient, uint256 amount) private {
(bool success, ) = recipient.call{value: amount}("");
require(success, "Failed to send ETH");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.0;
abstract contract Signature {
/**
* @dev Returns the address that signed a message given a signature.
* @param message The message signed.
* @param signature The signature.
*/
function getSignatureAddress(bytes32 message, bytes memory signature)
internal
pure
returns (address)
{
assert(signature.length == 65);
uint8 v;
bytes32 r;
bytes32 s;
assembly {
// First 32 bytes after length prefix.
r := mload(add(signature, 32))
// Next 32 bytes.
s := mload(add(signature, 64))
// Final byte.
v := byte(0, mload(add(signature, 96)))
}
return ecrecover(message, v, r, s);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| Sets the minimum and maximum token prices before the TGE starts. Also sets the deposit cap. min The minimum token price in ETH. max The maximum token price in ETH. _depositCap The ETH deposit cap./ | function setMinMaxForexPrices(
uint256 min,
uint256 max,
uint256 _depositCap
) external onlyOwner {
assert(!hasTgeBeenStarted());
require(max > min && _depositCap > max, "Invalid values");
minTokenPrice = min;
maxTokenPrice = max;
depositCap = _depositCap;
}
| 9,961,095 |
// ________ ________ ___ ________ ___ ___ ___ ___
//|\ ____\|\ __ \|\ \ |\ __ \ |\ \ / /|\ \ / /|
//\ \ \___|\ \ \|\ \ \ \ \ \ \|\ \ \ \ \/ / | \ \/ / /
// \ \ \ __\ \ __ \ \ \ \ \ __ \ \ \ / / \ \ / /
// \ \ \|\ \ \ \ \ \ \ \____\ \ \ \ \ / \/ \/ / /
// \ \_______\ \__\ \__\ \_______\ \__\ \__\/ /\ \ __/ / /
// \|_______|\|__|\|__|\|_______|\|__|\|__/__/ /\ __\\___/ /
// |__|/ \|__\|___|/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IERC721Receiver.sol";
import "./Hammies.sol";
import "./Fluff.sol";
contract Galaxy is Ownable, IERC721Receiver {
using SafeMath for uint256;
//Establish interface for Hammies
Hammies hammies;
//Establish interface for $Fluff
Fluff fluff;
event HammieStolen(address previousOwner, address newOwner, uint256 tokenId);
event HammieStaked(address owner, uint256 tokenId, uint256 status);
event HammieClaimed(address owner, uint256 tokenId);
/* Struct to track token info
Status is as follows:
0 - Unstaked
1 - Adventurer
2 - Pirate
3 - Salvager
*/
struct tokenInfo {
uint256 tokenId;
address owner;
uint256 status;
uint256 timeStaked;
}
// maps id to token info structure
mapping(uint256 => tokenInfo) public galaxy;
//Amount token id to amount stolen
mapping(uint256 => uint256) public fluffStolen;
//Daily $Fluff earned by adventurers
uint256 public adventuringFluffRate = 100 ether;
//Total number of adventurers staked
uint256 public totalAdventurersStaked = 0;
//Percent of $Fluff earned by adventurers that is kept
uint256 public adventurerShare = 50;
//Percent of $Fluff earned by adventurers that is stolen by pirates
uint256 public pirateShare = 50;
//5% chance a pirate gets lost each time it is unstaked
uint256 public chancePirateGetsLost = 5;
//Store tokenIds of all pirates staked
uint256[] public piratesStaked;
//Store Index of pirates staked
mapping(uint256 => uint256) public pirateIndices;
//Store tokenIds of all salvagers staked
uint256[] public salvagersStaked;
//Store Index of salvagers staked
mapping(uint256 => uint256) public salvagerIndices;
//1 day lock on staking
uint256 public minStakeTime = 1 days;
bool public staking = false;
//Used to map address to claimable Hammies from original Galaxy Contract
mapping (address => uint256) public claimableHammies;
//Used to keep track of total Hammies supply
uint256 public totalSupply = 4889;
constructor(){}
//Claim lost Hammies from Original Contract
function claimLostHammiesAndStake(uint256 _count, bool stake, uint256 status) public {
uint256 numReserved = claimableHammies[msg.sender];
require(numReserved > 0, "You do not have any claimable Hammies");
require(_count <= numReserved, "You do not have that many Claimable Hammies");
claimableHammies[msg.sender] = numReserved - _count;
for (uint256 i = 0; i < _count; i++) {
uint256 tokenId = totalSupply + i;
hammies.mintHammieForFluff();
if(stake){
galaxy[tokenId] = tokenInfo({
tokenId: tokenId,
owner: msg.sender,
status: status,
timeStaked: block.timestamp
});
if (status == 1)
totalAdventurersStaked++;
else if (status == 2){
piratesStaked.push(tokenId);
pirateIndices[tokenId] = piratesStaked.length - 1;
}
else if (status == 3){
salvagersStaked.push(tokenId);
salvagerIndices[tokenId] = salvagersStaked.length - 1;
}
} else {
hammies.safeTransferFrom(address(this), msg.sender, tokenId);
}
}
uint256 fluffOwed = _count * 100 ether;
fluff.mint(msg.sender, fluffOwed);
totalSupply += _count;
}
//Edit Claimable Hammies per person
function editHammiesClaimable(address[] calldata addresses, uint256[] calldata count) external onlyOwner {
for(uint256 i; i < addresses.length; i++){
claimableHammies[addresses[i]] = count[i];
}
}
//Mint Hammies for Fluff
function mintHammieForFluff(bool stake, uint256 status) public {
require(staking, "Staking is paused");
fluff.burn(msg.sender, getFluffCost(totalSupply));
hammies.mintHammieForFluff();
uint256 tokenId = totalSupply;
totalSupply++;
if(stake){
galaxy[tokenId] = tokenInfo({
tokenId: tokenId,
owner: msg.sender,
status: status,
timeStaked: block.timestamp
});
if (status == 1)
totalAdventurersStaked++;
else if (status == 2){
piratesStaked.push(tokenId);
pirateIndices[tokenId] = piratesStaked.length - 1;
}
else if (status == 3){
salvagersStaked.push(tokenId);
salvagerIndices[tokenId] = salvagersStaked.length - 1;
}
} else {
hammies.safeTransferFrom(address(this), msg.sender, tokenId);
}
}
function getFluffCost(uint256 supply) internal pure returns (uint256 cost){
if (supply < 5888)
return 100 ether;
else if (supply < 6887)
return 200 ether;
else if (supply < 7887)
return 400 ether;
else if (supply < 8887)
return 800 ether;
}
//-----------------------------------------------------------------------------//
//------------------------------Staking----------------------------------------//
//-----------------------------------------------------------------------------//
/*sends any number of Hammies to the galaxy
ids -> list of hammie ids to stake
Status == 1 -> Adventurer
Status == 2 -> Pirate
Status == 3 -> Salvager
*/
function sendManyToGalaxy(uint256[] calldata ids, uint256 status) external {
for(uint256 i = 0; i < ids.length; i++){
require(hammies.ownerOf(ids[i]) == msg.sender, "Not your Hammie");
require(staking, "Staking is paused");
galaxy[ids[i]] = tokenInfo({
tokenId: ids[i],
owner: msg.sender,
status: status,
timeStaked: block.timestamp
});
emit HammieStaked(msg.sender, ids[i], status);
hammies.transferFrom(msg.sender, address(this), ids[i]);
if (status == 1)
totalAdventurersStaked++;
else if (status == 2){
piratesStaked.push(ids[i]);
pirateIndices[ids[i]] = piratesStaked.length - 1;
}
else if (status == 3){
salvagersStaked.push(ids[i]);
salvagerIndices[ids[i]] = salvagersStaked.length - 1;
}
}
}
function unstakeManyHammies(uint256[] calldata ids) external {
for(uint256 i = 0; i < ids.length; i++){
tokenInfo memory token = galaxy[ids[i]];
require(token.owner == msg.sender, "Not your Hammie");
require(hammies.ownerOf(ids[i]) == address(this), "Hammie must be staked in order to claim");
require(staking, "Staking is paused");
require(block.timestamp - token.timeStaked >= minStakeTime, "1 day stake lock");
_claim(msg.sender, ids[i]);
if (token.status == 1){
totalAdventurersStaked--;
}
else if (token.status == 2){
uint256 lastPirate = piratesStaked[piratesStaked.length - 1];
piratesStaked[pirateIndices[ids[i]]] = lastPirate;
pirateIndices[lastPirate] = pirateIndices[ids[i]];
piratesStaked.pop();
}
else if (token.status == 3){
uint256 lastSalvager = salvagersStaked[salvagersStaked.length - 1];
salvagersStaked[salvagerIndices[ids[i]]] = lastSalvager;
salvagerIndices[lastSalvager] = salvagerIndices[ids[i]];
salvagersStaked.pop();
}
emit HammieClaimed(address(this), ids[i]);
//retrieve token info again to account for stolen Hammies
tokenInfo memory newToken = galaxy[ids[i]];
hammies.safeTransferFrom(address(this), newToken.owner, ids[i]);
galaxy[ids[i]] = tokenInfo({
tokenId: ids[i],
owner: newToken.owner,
status: 0,
timeStaked: block.timestamp
});
}
}
function claimManyHammies(uint256[] calldata ids) external {
for(uint256 i = 0; i < ids.length; i++){
tokenInfo memory token = galaxy[ids[i]];
require(token.owner == msg.sender, "Not your hammie");
require(hammies.ownerOf(ids[i]) == address(this), "Hammie must be staked in order to claim");
require(staking, "Staking is paused");
_claim(msg.sender, ids[i]);
emit HammieClaimed(address(this), ids[i]);
//retrieve token info again to account for stolen Hammies
tokenInfo memory newToken = galaxy[ids[i]];
galaxy[ids[i]] = tokenInfo({
tokenId: ids[i],
owner: newToken.owner,
status: newToken.status,
timeStaked: block.timestamp
});
}
}
function _claim(address owner, uint256 tokenId) internal {
tokenInfo memory token = galaxy[tokenId];
if (token.status == 1){
if(piratesStaked.length > 0){
uint256 fluffGathered = getPendingFluff(tokenId);
fluff.mint(owner, fluffGathered.mul(adventurerShare).div(100));
stealFluff(fluffGathered.mul(pirateShare).div(100));
}
else {
fluff.mint(owner, getPendingFluff(tokenId));
}
}
else if (token.status == 2){
uint256 roll = randomIntInRange(tokenId, 100);
if(roll > chancePirateGetsLost || salvagersStaked.length == 0){
fluff.mint(owner, fluffStolen[tokenId]);
fluffStolen[tokenId ]= 0;
} else{
getNewOwnerForPirate(roll, tokenId);
}
}
}
//Public function to view pending $fluff earnings for Adventurers.
function getFluffEarnings(uint256 id) public view returns(uint256) {
return getPendingFluff(id);
}
//Passive earning of $Fluff, 100 $Fluff per day
function getPendingFluff(uint256 id) internal view returns(uint256) {
tokenInfo memory token = galaxy[id];
return (block.timestamp - token.timeStaked) * 100 ether / 1 days;
}
//Returns a pseudo-random integer between 0 - max
function randomIntInRange(uint256 seed, uint256 max) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
))) % max;
}
//Return new owner of lost pirate from current salvagers
function stealFluff(uint256 amount) internal{
uint256 roll = randomIntInRange(amount, piratesStaked.length);
fluffStolen[piratesStaked[roll]] += amount;
}
//Return new owner of lost pirate from current salvagers
function getNewOwnerForPirate(uint256 seed, uint256 tokenId) internal{
tokenInfo memory pirate = galaxy[tokenId];
uint256 roll = randomIntInRange(seed, salvagersStaked.length);
tokenInfo memory salvager = galaxy[salvagersStaked[roll]];
emit HammieStolen(pirate.owner, salvager.owner, tokenId);
galaxy[tokenId] = tokenInfo({
tokenId: tokenId,
owner: salvager.owner,
status: 2,
timeStaked: block.timestamp
});
fluff.mint(salvager.owner, fluffStolen[tokenId]);
fluffStolen[tokenId] = 0;
}
function getTotalSalvagersStaked() public view returns (uint256) {
return salvagersStaked.length;
}
function getTotalPiratesStaked() public view returns (uint256) {
return piratesStaked.length;
}
//Set address for Hammies
function setHammieAddress(address hammieAddr) external onlyOwner {
hammies = Hammies(hammieAddr);
}
//Set address for $Fluff
function setFluffAddress(address fluffAddr) external onlyOwner {
fluff = Fluff(fluffAddr);
}
//Start/Stop staking
function toggleStaking() public onlyOwner {
staking = !staking;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
} | Return new owner of lost pirate from current salvagers | function getNewOwnerForPirate(uint256 seed, uint256 tokenId) internal{
tokenInfo memory pirate = galaxy[tokenId];
uint256 roll = randomIntInRange(seed, salvagersStaked.length);
tokenInfo memory salvager = galaxy[salvagersStaked[roll]];
emit HammieStolen(pirate.owner, salvager.owner, tokenId);
galaxy[tokenId] = tokenInfo({
tokenId: tokenId,
owner: salvager.owner,
status: 2,
timeStaked: block.timestamp
});
fluff.mint(salvager.owner, fluffStolen[tokenId]);
fluffStolen[tokenId] = 0;
}
| 1,154,573 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {ConfigContract} from "./ConfigContract.sol";
import {
BatcherContract,
BatchConfig,
TransactionType
} from "./BatcherContract.sol";
struct CipherExecutionReceipt {
bool executed;
address executor;
uint64 halfStep;
bytes32 cipherBatchHash;
bytes32 batchHash;
}
/// @title A contract that serves as the entry point of batch execution
/// @dev Batch execution is carried out in two separate steps: Execution of the encrypted portion,
/// followed by execution of the plaintext portion. Thus, progress is counted in half steps (0
/// and 1 for batch 0, 2 and 3 for batch 1, and so on).
contract ExecutorContract {
/// @notice The event emitted after a batch execution half step has been carried out.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// the one responsible for emitting the event.
/// @param batchHash The hash of the executed batch (consisting of plaintext transactions).
event BatchExecuted(uint64 numExecutionHalfSteps, bytes32 batchHash);
/// @notice The event emitted after execution of the cipher portion of a batch has been skipped.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// this one.
event CipherExecutionSkipped(uint64 numExecutionHalfSteps);
event TransactionFailed(uint64 txIndex, bytes32 txHash, bytes data);
ConfigContract public configContract;
BatcherContract public batcherContract;
uint64 public numExecutionHalfSteps;
mapping(uint64 => CipherExecutionReceipt) public cipherExecutionReceipts;
constructor(
ConfigContract configContractAddress,
BatcherContract batcherContractAddress
) {
configContract = configContractAddress;
batcherContract = batcherContractAddress;
}
/// @notice Execute the cipher portion of a batch.
/// @param batchIndex The index of the batch
/// @param cipherBatchHash The hash of the batch (consisting of encrypted transactions)
/// @param transactions The sequence of (decrypted) transactions to execute.
/// @param keyperIndex The index of the keyper calling the function.
/// @notice Execution is only performed if `cipherBatchHash` matches the hash in the batcher
/// contract and the batch is active and completed.
function executeCipherBatch(
uint64 batchIndex,
bytes32 cipherBatchHash,
bytes[] calldata transactions,
uint64 keyperIndex
) public {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
// Check that it's a cipher batch turn
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex =
configContract.configIndexForBatchIndex(batchIndex);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector =
configContract.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit =
configContract.configTransactionGasLimit(configIndex);
// Check that batching is active
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, uint64 end, uint64 executionTimeout) =
configContract.batchBoundaryBlocks(configIndex, batchIndex);
// skip cipher execution if we reached the execution timeout.
if (block.number >= executionTimeout) {
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
return;
}
require(
block.number >= end,
"ExecutorContract: batch is not closed yet"
);
// Check that caller is keyper
uint64 numKeypers = configContract.configNumKeypers(configIndex);
require(
keyperIndex < numKeypers,
"ExecutorContract: keyper index out of bounds"
);
address keyperAtIndex =
configContract.configKeypers(configIndex, keyperIndex);
require(
msg.sender == keyperAtIndex,
"ExecutorContract: sender is not specified keyper"
);
// Check the cipher batch hash is correct
require(
cipherBatchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Cipher),
"ExecutorContract: incorrect cipher batch hash"
);
// Check the number of transactions is zero iff we provide the ZERO_HASH
require(
(cipherBatchHash == bytes32(0) && transactions.length == 0) ||
(cipherBatchHash != bytes32(0) && transactions.length > 0),
"ExecutorContract: cipherBatchHash should be zero iff transactions is empty"
);
// Execute the batch
bytes32 batchHash =
executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
cipherExecutionReceipts[
numExecutionHalfSteps
] = CipherExecutionReceipt({
executed: true,
executor: msg.sender,
halfStep: numExecutionHalfSteps,
cipherBatchHash: cipherBatchHash,
batchHash: batchHash
});
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
/// @notice Skip execution of the cipher portion of a batch.
/// @notice This is only possible if successful execution has not been carried out in time
/// (according to the execution timeout defined in the config)
function skipCipherExecution(uint64 batchIndex) external {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex =
configContract.configIndexForBatchIndex(batchIndex);
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, , uint64 executionTimeout) =
configContract.batchBoundaryBlocks(configIndex, batchIndex);
require(
block.number >= executionTimeout,
"ExecutorContract: execution timeout not reached yet"
);
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
}
/// @notice Execute the plaintext portion of a batch.
/// @param batchIndex The index of the batch
/// @param transactions The array of plaintext transactions in the batch.
/// @notice This is a trustless operation since `transactions` will be checked against the
/// (plaintext) batch hash from the batcher contract.
function executePlainBatch(uint64 batchIndex, bytes[] calldata transactions)
external
{
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 1,
"ExecutorContract: unexpected half step"
);
uint64 configIndex =
configContract.configIndexForBatchIndex(batchIndex);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector =
configContract.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit =
configContract.configTransactionGasLimit(configIndex);
// Since the cipher part of the batch has already been executed or skipped and the
// config cannot be changed anymore (since the batching period is over), the following
// checks remain true.
assert(configContract.batchingActive(configIndex));
(, uint64 end, ) =
configContract.batchBoundaryBlocks(configIndex, batchIndex);
assert(block.number >= end);
bytes32 batchHash =
executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
require(
batchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Plain),
"ExecutorContract: batch hash does not match"
);
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
function executeTransactions(
address targetAddress,
bytes4 targetFunctionSelector,
uint64 gasLimit,
bytes[] calldata transactions
) private returns (bytes32) {
bytes32 batchHash;
for (uint64 i = 0; i < transactions.length; i++) {
bytes memory callData =
abi.encodeWithSelector(targetFunctionSelector, transactions[i]);
// call target function, ignoring any errors
(bool success, bytes memory returnData) =
targetAddress.call{gas: gasLimit}(callData);
if (!success) {
emit TransactionFailed({
txIndex: i,
txHash: keccak256(transactions[i]),
data: returnData
});
}
batchHash = keccak256(abi.encodePacked(transactions[i], batchHash));
}
return batchHash;
}
function getReceipt(uint64 halfStep)
public
view
returns (CipherExecutionReceipt memory)
{
return cipherExecutionReceipts[halfStep];
}
}
| call target function, ignoring any errors | function executeTransactions(
address targetAddress,
bytes4 targetFunctionSelector,
uint64 gasLimit,
bytes[] calldata transactions
) private returns (bytes32) {
bytes32 batchHash;
for (uint64 i = 0; i < transactions.length; i++) {
bytes memory callData =
abi.encodeWithSelector(targetFunctionSelector, transactions[i]);
(bool success, bytes memory returnData) =
if (!success) {
emit TransactionFailed({
txIndex: i,
txHash: keccak256(transactions[i]),
data: returnData
});
}
batchHash = keccak256(abi.encodePacked(transactions[i], batchHash));
}
return batchHash;
}
| 15,856,360 |
/**
*Submitted for verification at Etherscan.io on 2021-04-01
*/
// File: contracts/token/interfaces/IERC20Token.sol
pragma solidity 0.4.26;
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {this;}
function symbol() public view returns (string) {this;}
function decimals() public view returns (uint8) {this;}
function totalSupply() public view returns (uint256) {this;}
function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
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);
}
// File: contracts/utility/Utils.sol
pragma solidity 0.4.26;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
/**
* constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
// File: contracts/utility/SafeMath.sol
pragma solidity 0.4.26;
/**
* @dev Library for basic math operations with overflow/underflow protection
*/
library SafeMath {
/**
* @dev returns the sum of _x and _y, reverts if the calculation overflows
*
* @param _x value 1
* @param _y value 2
*
* @return sum
*/
function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
require(z >= _x);
return z;
}
/**
* @dev returns the difference of _x minus _y, reverts if the calculation underflows
*
* @param _x minuend
* @param _y subtrahend
*
* @return difference
*/
function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y);
return _x - _y;
}
/**
* @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
*
* @param _x factor 1
* @param _y factor 2
*
* @return product
*/
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
// gas optimization
if (_x == 0)
return 0;
uint256 z = _x * _y;
require(z / _x == _y);
return z;
}
/**
* ev Integer division of two numbers truncating the quotient, reverts on division by zero.
*
* aram _x dividend
* aram _y divisor
*
* eturn quotient
*/
function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_y > 0);
uint256 c = _x / _y;
return c;
}
}
// File: contracts/token/ERC20Token.sol
pragma solidity 0.4.26;
/**
* @dev ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/**
* @dev triggered when tokens are transferred between wallets
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf
*
* @param _owner wallet that approves the allowance
* @param _spender wallet that receives the allowance
* @param _value allowance amount
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _decimals decimal points, for display purposes
* @param _totalSupply total supply of token units
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceOf[msg.sender] = _totalSupply;
}
/**
* @dev send coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev an account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev allow another account/contract to spend some tokens on your behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
// File: contracts/utility/interfaces/IOwned.sol
pragma solidity 0.4.26;
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {this;}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
// File: contracts/token/interfaces/ISmartToken.sol
pragma solidity 0.4.26;
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
// File: contracts/utility/Owned.sol
pragma solidity 0.4.26;
/**
* @dev Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
require(msg.sender == owner);
_;
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.4.26;
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
// File: contracts/token/interfaces/INonStandardERC20.sol
pragma solidity 0.4.26;
/*
ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve
*/
contract INonStandardERC20 {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {this;}
function symbol() public view returns (string) {this;}
function decimals() public view returns (uint8) {this;}
function totalSupply() public view returns (uint256) {this;}
function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
function transfer(address _to, uint256 _value) public;
function transferFrom(address _from, address _to, uint256 _value) public;
function approve(address _spender, uint256 _value) public;
}
// File: contracts/utility/TokenHolder.sol
pragma solidity 0.4.26;
/**
* @dev We consider every contract to be a 'token holder' since it's currently not possible
* for a contract to deny receiving tokens.
*
* The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
* the owner to send tokens that were sent to the contract by mistake back to their sender.
*
* Note that we use the non standard ERC-20 interface which has no return value for transfer
* in order to support both non standard as well as standard token contracts.
* see https://github.com/ethereum/solidity/issues/4116
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
* @dev initializes a new TokenHolder instance
*/
constructor() public {
}
/**
* @dev withdraws tokens held by the contract and sends them to an account
* can only be called by the owner
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
INonStandardERC20(_token).transfer(_to, _amount);
}
}
// File: contracts/token/SmartToken.sol
pragma solidity 0.4.26;
/**
* @dev Smart Token
*
* 'Owned' is specified here for readability reasons
*/
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
using SafeMath for uint256;
string public version = '0.3';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
/**
* @dev triggered when a smart token is deployed
* the _token address is defined for forward compatibility, in case the event is trigger by a factory
*
* @param _token new smart token address
*/
event NewSmartToken(address _token);
/**
* @dev triggered when the total supply is increased
*
* @param _amount amount that gets added to the supply
*/
event Issuance(uint256 _amount);
/**
* @dev triggered when the total supply is decreased
*
* @param _amount amount that gets removed from the supply
*/
event Destruction(uint256 _amount);
/**
* @dev initializes a new SmartToken instance
*
* @param _name token name
* @param _symbol token short symbol, minimum 1 character
* @param _decimals for display purposes only
*/
constructor(string _name, string _symbol, uint8 _decimals)
public
ERC20Token(_name, _symbol, _decimals, 0)
{
emit NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
* @dev disables/enables transfers
* can only be called by the contract owner
*
* @param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
* @dev increases the token supply and sends the new tokens to an account
* can only be called by the contract owner
*
* @param _to account to receive the new amount
* @param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = totalSupply.add(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
emit Issuance(_amount);
emit Transfer(this, _to, _amount);
}
/**
* @dev removes tokens from an account and decreases the token supply
* can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
*
* @param _from account to remove the amount from
* @param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner); // validate input
balanceOf[_from] = balanceOf[_from].sub(_amount);
totalSupply = totalSupply.sub(_amount);
emit Transfer(_from, this, _amount);
emit Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
* @dev send coins
* throws on any error rather then return a false flag to minimize user errors
* in addition to the standard checks, the function throws if transfers are disabled
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
/**
* @dev an account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
* in addition to the standard checks, the function throws if transfers are disabled
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
} | ev Integer division of two numbers truncating the quotient, reverts on division by zero. aram _x dividend aram _y divisor eturn quotient/ | function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_y > 0);
uint256 c = _x / _y;
return c;
}
| 2,415,126 |
// File: contracts/interface/IERC165.sol
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
*
*
* ,,,,,,,,
* ,,,,,,,,,,,
* ,,,,,,,,,,,,
* ,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,,,
* ,,,,,,,,,,,,,,,,,,,
* &/////////,,,,,,,,,,,,,,,,,,,,
* &////////////,,,,,,,,,,,,,,,,,,,,,
* %//&%**************,,,,,,,,,,,,,,,,
* &************************,,,,,,,,,,,,*
* (*****************************%,,,,,,,,,***&
* &**********************************(,,,,,,********
* &************************((&//////////(//&&,&**********
* &*******************((#////////////////(/////&(&**********
* &***************&((,#//////////////////(//////#((((**********
* ***********%((# (//////////////////(///////& %((&*********&
* #%&(## &///////////////////(//////// (((**********
* &///////////////////(/////////& ((**********%
* /////////////////////(////////// &(&**********
* &/twitter: [at]alexandraparfen // ((**********
* ///////opeansea: [at]parfene /////// &(********&
* &//////alexandraparfene[at]me.com///// &(********
* %%%&/////////////////////////////& &(((((&
* %%%&///////////////////////&
* &/////////%&%
*
*
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
// File: contracts/interface/IERC721.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;
}
// File: contracts/interface/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: contracts/interface/IERC721Metadata.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);
}
// File: contracts/util/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
// File: contracts/util/Strings.sol
/**
* @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);
}
}
// File: contracts/standard/ERC165.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;
}
}
// File: contracts/core/ERC721.sol
/**
* @dev Implementation of Non-Fungible Token.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
// The artist associated with the collection.
string private _creator;
address public immutable _owner;
// Token name.
string private _name;
// Minting process state.
bool public _finalized;
// Token symbol.
string private _symbol;
string private _baseURI;
uint256 public immutable _operand;
uint256 public immutable _typeCount;
// Mapping from type to name of token.
mapping(uint256 => string) private _typeName;
// Mapping from type to IPFS hash of canonical artifcat file.
mapping(uint256 => string) private _typeIPFSHashes;
// Mapping from type to token artifact location.
mapping(uint256 => string) private _typeURI;
// Mapping from token ID to owner address.
mapping (uint256 => address) internal _owners;
// Mapping owner address to token count, by aggregating all _typeCount NFTs in the contact.
mapping (address => uint256) internal _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 token collection.
*/
constructor() {
_name = "The Boring Bucket Hat";
_symbol = "BORING";
_creator = "Alexandra Parfene";
_owner = msg.sender;
_typeCount = 5;
_operand = 10000;
_baseURI = "https://gist.githubusercontent.com/parfene/";
_typeName[1] = "Unit P4";
_typeIPFSHashes[1] = "QmSFdYSXWSczFqTuwjjvbjzb9kDME1xXWHHopZoXDJDb4B";
_typeURI[1] = "b98d6ff7b0cc6c0e911d3954e29dd090/raw/258e588039400689dc4901e28c04563b392ecd6e/unit_p4.json";
_typeName[2] = "Unit P3";
_typeIPFSHashes[2] = "QmQaGqyUxW8WzbGm77ehm9pp8iSz5af18BPoJb6hji3WX4";
_typeURI[2] = "f0247e710fa364f2e7c43d5844068bbf/raw/9ca1d517ccbe85820eac5a6203fc7bc295a25bff/unit_p3.json";
_typeName[3] = "Unit R3";
_typeIPFSHashes[3] = "QmfTAZyyv7HYecKmBEvPbPsP6uKkgZsRbdH8bz7xq6N5W1";
_typeURI[3] = "faa5e1a3915979fd8cb43c41fdc43a30/raw/fbdc8275312761c1c78d1433560ec2dab0b2a60b/unit_r3.json";
_typeName[4] = "Unit W3";
_typeIPFSHashes[4] = "QmdAYsrnuWL1NdvpaMvZnWU7TVpWQoqsfhZobWANMBFJZ8";
_typeURI[4] = "2d59ea3e82d6c1475acbf98ad0395a18/raw/d96129be81c79b88277d121ced88a88b3c491247/unit_w3.json";
_typeName[5] = "Unit B3";
_typeIPFSHashes[5] = "Qme6U9zacbpCfgyGwwyFiyUFYWD9ZHMMMdEnBMwrETrwxR";
_typeURI[5] = "081c2f2e29a459f46d04731e9e02bee7/raw/caefd2620d5d7feb7492417ff2e92bc47ccd2a1b/unit_b3.json";
}
modifier onlyOwner() {
require(msg.sender == _owner);
_;
}
/**
* @dev Prevent the minting of additional NFTs.
*/
function setFinalized() public onlyOwner {
require(_finalized == false, "ERC721: only finalizable once");
_finalized = true;
}
/**
* @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 The artist of this collection.
*/
function creator() public view virtual returns (string memory) {
return _creator;
}
/**
* @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 Returns an IPFS hash for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query.
* @return IPFS hash for this (_typeCount) NFT.
*/
function tokenIPFSHash(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: IPFS hash query for nonexistent token");
uint256 countType = _getTypeId(tokenId);
return _typeIPFSHashes[countType];
}
/**
* @dev Returns the link to artificat location for a given token by 'tokenId'.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query.
* @return The location where the artifact assets are stored.
*/
function tokenURI(uint256 tokenId) external view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
uint256 countType = _getTypeId(tokenId);
return string(abi.encodePacked(_baseURI, _typeURI[countType]));
}
/**
* @dev Determine which NFT in the contract (_typeCount) is associated
* with this 'tokenId'.
*/
function _getTypeId(uint256 tokenId) private view returns (uint256) {
return uint256(tokenId / _operand);
}
/**
* @dev Returns the Name for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenName(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token");
uint256 countType = _getTypeId(tokenId);
return _typeName[countType];
}
/**
* @dev Base URI for computing {tokenURI}.
*/
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURI = baseURI_;
}
/**
* @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 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);
// 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");
// 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 (isContract(to)) {
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 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 Start with 10000, or 10001
*
*/
function mint(address[] memory owners, uint256 typeCount) public onlyOwner {
require(!_finalized, "ERC721: minting concluded");
for(uint8 index = 0; index < owners.length; index++) {
uint256 token_0001 = typeCount + index;
address owner_0001 = owners[index];
_owners[token_0001] = owner_0001;
_balances[owner_0001] = 1;
emit Transfer(address(0), owner_0001, token_0001);
}
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
} | Returns the Name for a given token ID. Throws if the token ID does not exist. May return an empty string. tokenId uint256 ID of the token to query/ | function tokenName(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token");
uint256 countType = _getTypeId(tokenId);
return _typeName[countType];
}
| 4,812,101 |
pragma solidity ^0.4.24;
// XXX enable returning structs from internal functions
pragma experimental ABIEncoderV2;
import {DSToken as Token} from "contracts/dappsys.sol";
// External interface
interface PreimageManager {
function submitPreimage(bytes32 x) external;
function revealedBefore(bytes32 h, uint T) external returns (bool);
}
// Note: Initial version does NOT support concurrent conditional payments!
contract SpritesRegistry {
// Blocks for grace period
uint constant DELTA = 10;
struct Player {
address addr;
int credit;
uint withdrawal;
uint withdrawn;
uint deposit;
}
enum Status {OK, PENDING}
struct Payment {
uint amount;
uint expiry;
address recipient;
bytes32 preimageHash;
}
struct Channel {
address tokenAddress;
Player left;
Player right;
int bestRound;
Status status;
uint deadline;
// Conditional payment
Payment payment;
}
// Events
event EventInit(uint channelID);
event EventUpdate(uint channelID, int round);
event EventPending(uint channelID, uint start, uint deadline);
// Utility functions
modifier onlyplayers (uint channelID){
Channel storage channel = channels[channelID];
require( channel.left.addr == msg.sender || channel.right.addr == msg.sender);
_;
}
function max(uint a, uint b) internal pure returns (uint) {if (a > b) return a; else return b;}
function min(uint a, uint b) internal pure returns (uint) {if (a < b) return a; else return b;}
// providing this separtely to test from application code
function recoverAddress(bytes32 messageHash, uint[3] sig) public pure returns (address) {
uint8 V = uint8(sig[0]);
bytes32 R = bytes32(sig[1]);
bytes32 S = bytes32(sig[2]);
return ecrecover(messageHash, V, R, S);
}
function isSignatureOkay(address pub, bytes32 messageHash, uint[3] sig) public pure returns (bool) {
require(pub == recoverAddress(messageHash, sig));
return true;
}
// Contract global data
mapping(uint => Channel) public channels;
PreimageManager pm;
uint channelCounter;
function sha3int(int r) public pure returns (bytes32) {
return keccak256(r);
}
function SpritesRegistry(address preimageManagerAddress) public
{
pm = PreimageManager(preimageManagerAddress);
channelCounter = 0;
}
function createChannel(address other, address tokenAddress) public returns (uint) {
uint channelID = channelCounter;
// using memory here reduces gas cost from ~ 300k to 200k
Channel memory channel;
Payment memory payment;
channel.tokenAddress = tokenAddress;
channel.left.addr = msg.sender;
channel.right.addr = other;
channel.bestRound = -1;
channel.status = Status.OK;
channel.deadline = 0; // not sure
payment.expiry = 0;
payment.amount = 0;
payment.preimageHash = bytes32(0);
payment.recipient = 0;
channel.payment = payment;
channels[channelID] = channel;
channelCounter += 1;
// can't return from state modifying function
EventInit(channelID);
}
function lookupPlayer(uint channelID) internal view onlyplayers(channelID) returns (Player storage) {
Channel storage channel = channels[channelID];
if (channel.left.addr == msg.sender)
return channel.left;
else
return channel.right;
}
function lookupOtherPlayer(uint channelID) internal view onlyplayers(channelID) returns (Player storage) {
Channel storage channel = channels[channelID];
if (channel.left.addr == msg.sender)
return channel.right;
else
return channel.left;
}
// Increment on new deposit
// user first needs to approve us to transfer tokens
function deposit(uint channelID, uint amount) public onlyplayers(channelID) returns (bool) {
Channel storage channel = channels[channelID];
bool status = Token(channel.tokenAddress).transferFrom(msg.sender, this, amount);
// return status 0 if transfer failed, 1 otherwise
require(status == true);
Player storage player = lookupPlayer(channelID);
player.deposit += amount;
}
function getDeposit(uint channelID) public view returns (uint) {
return lookupPlayer(channelID).deposit;
}
function getStatus(uint channelID) public view returns (Status) {
return channels[channelID].status;
}
function getDeadline(uint channelID) public view returns (uint) {
return channels[channelID].deadline;
}
function getWithdrawn(uint channelID) public view returns (uint) {
return lookupPlayer(channelID).withdrawn;
}
// Increment on withdrawal
// XXX does currently not support incremental withdrawals
// XXX check if failing assert undoes all changes made in tx
function withdraw(uint channelID) public onlyplayers(channelID) {
Player storage player = lookupPlayer(channelID);
uint toWithdraw = player.withdrawal - player.withdrawn;
require(Token(channels[channelID].tokenAddress).transferFrom(this, msg.sender, toWithdraw));
player.withdrawn = player.withdrawal;
}
// XXX the experimental ABI encoder supports return struct, but as of 2018 04 08
// web3.py does not seem to support decoding structs.
function getState(uint channelID)
public constant onlyplayers(channelID)
returns (
uint[2] deposits,
int[2] credits,
uint[2] withdrawals,
int bestRound,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
)
{
Player storage player = lookupPlayer(channelID);
Player storage other = lookupOtherPlayer(channelID);
// Channel storage channel = channels[channelID];
Payment storage payment = channels[channelID].payment;
bestRound = channels[channelID].bestRound;
preimageHash = payment.preimageHash;
recipient = payment.recipient;
amount = payment.amount;
expiry = payment.expiry;
deposits[0] = player.deposit;
deposits[1] = other.deposit;
credits[0] = player.credit;
credits[1] = other.credit;
withdrawals[0] = player.withdrawal;
withdrawals[1] = other.withdrawal;
}
function compute_hash(
uint channelID,
int[2] credits,
uint[2] withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
) private pure returns (bytes32) {
// message length is 32 * number of (flattened) arguments to keccak
bytes memory prefix = "\x19Ethereum Signed Message:\n320";
return keccak256(
prefix,
channelID,
credits,
withdrawals,
round,
preimageHash,
// Addresses are 20 bytes, but currently the client code
// pads every input to 32 bytes.
bytes32(recipient),
amount,
expiry
);
}
function verifyUpdate(
uint channelID,
uint[3] sig,
int[2] credits,
uint[2] withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
)
public onlyplayers(channelID)
view {
// Do not allow overpayment.
// TODO conversion? save math?
// We can't check for overpayment because the chain state might
// not be up to date?
// Verify the update does not include an overpayment needs to be done by client?
// assert(int(amount) <= int(other.deposit) + credits[0]);
// Only update to states with larger round number
require(round > channels[channelID].bestRound);
// Check the signature of the other party
bytes32 messageHash = compute_hash(
channelID, credits, withdrawals, round, preimageHash, recipient, amount, expiry
);
Player storage other = lookupOtherPlayer(channelID);
isSignatureOkay(other.addr, messageHash, sig);
}
function update(
uint channelID,
uint[3] sig,
int[2] credits,
uint[2] withdrawals,
int round,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
) public onlyplayers(channelID)
{
verifyUpdate(channelID, sig, credits, withdrawals, round, preimageHash, recipient, amount, expiry);
updatePayment(channelID, preimageHash, recipient, amount, expiry);
updatePlayers(channelID, credits, withdrawals);
updateChannel(channelID, round);
EventUpdate(channelID, round);
}
function updatePlayers(
uint channelID,
int[2] credits,
uint[2] withdrawals
) private {
Player storage player = lookupPlayer(channelID);
Player storage other = lookupOtherPlayer(channelID);
// Can only submit a message signed by the _other_ party hence the reverse order.
player.credit = credits[1];
player.withdrawal = withdrawals[1];
other.credit = credits[0];
other.withdrawal = withdrawals[0];
// prevent over withdrawals
// TODO conversion? save math?
assert(int(player.withdrawal) <= int(player.deposit) + player.credit);
// FAIL!
assert(int(other.withdrawal) <= int(other.deposit) + other.credit);
}
function updateChannel(uint channelID, int round) private {
channels[channelID].bestRound = round;
}
function updatePayment(
uint channelID,
bytes32 preimageHash,
address recipient,
uint amount,
uint expiry
) private {
Payment storage payment = channels[channelID].payment;
payment.preimageHash = preimageHash;
payment.recipient = recipient;
payment.amount = amount;
payment.expiry = expiry;
}
// Causes a timeout for the finalize time
function trigger(uint channelID) public onlyplayers(channelID) {
Channel storage channel = channels[channelID];
require(channel.status == Status.OK);
channel.status = Status.PENDING;
channel.deadline = block.number + DELTA;
// Set the deadline for collecting inputs or updates
EventPending(channelID, block.number, channel.deadline);
}
function finalize(uint channelID) public onlyplayers(channelID) {
Channel storage channel = channels[channelID];
Payment storage payment = channel.payment;
require(channel.status == Status.PENDING);
require(block.number > channel.deadline);
// Finalize is safe to call multiple times
// If "trigger" occurs before a hashlock expires, finalize will need to be called again
if (payment.amount > 0 && block.number > payment.expiry) {
bool revealed = pm.revealedBefore(payment.preimageHash, payment.expiry);
bool paymentToRight = payment.recipient == channel.right.addr;
bool sendToRight = (revealed && paymentToRight) || (!revealed && !paymentToRight);
if (sendToRight) {
channel.right.withdrawal += payment.amount;
} else {
channel.left.withdrawal += payment.amount;
}
// reset the in-flight payment that is now resolved
payment.amount = 0;
payment.preimageHash = bytes32(0);
payment.expiry = 0;
payment.recipient = 0x0;
}
// Withdraw the maximum amounts left in the channel
channel.left.withdrawal += uint(int(channel.left.deposit) + channel.left.credit);
channel.right.withdrawal += uint(int(channel.right.deposit) + channel.right.credit);
channel.left.credit = - int(channel.left.deposit);
channel.right.credit = - int(channel.right.deposit);
}
}
| using memory here reduces gas cost from ~ 300k to 200k can't return from state modifying function | function createChannel(address other, address tokenAddress) public returns (uint) {
uint channelID = channelCounter;
Channel memory channel;
Payment memory payment;
channel.tokenAddress = tokenAddress;
channel.left.addr = msg.sender;
channel.right.addr = other;
channel.bestRound = -1;
channel.status = Status.OK;
payment.expiry = 0;
payment.amount = 0;
payment.preimageHash = bytes32(0);
payment.recipient = 0;
channel.payment = payment;
channels[channelID] = channel;
channelCounter += 1;
EventInit(channelID);
}
| 2,560,220 |
./partial_match/1/0x157ED4Dcd657d17Aa2c3dCA31f30043e8Eff4f2E/sources/contracts/libraries/LiquidityHelper.sol | Calculates the liquidity amount using current ranges _pool Instance of the pool _tickLower Lower tick _tickUpper Upper tick _liquidity Liquidity of the pool/ get sqrtRatios required to calculate liquidity calculate liquidity needs to be added | function getAmountsForLiquidity(
IUniswapV3Pool _pool,
int24 _tickLower,
int24 _tickUpper,
uint128 _liquidity
) public view returns (uint256 amount0, uint256 amount1) {
(uint160 sqrtRatioX96, , , , , , ) = _pool.slot0();
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
_liquidity
);
}
| 3,598,302 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.11;
import "../Rollup.sol";
import "./IRollupFacets.sol";
import "../../bridge/interfaces/IOutbox.sol";
import "../../bridge/interfaces/ISequencerInbox.sol";
import "../../libraries/Whitelist.sol";
import "@openzeppelin/contracts/proxy/UpgradeableBeacon.sol";
contract RollupAdminFacet is RollupBase, IRollupAdmin {
/**
* Functions are only to reach this facet if the caller is the owner
* so there is no need for a redundant onlyOwner check
*/
/**
* @notice Add a contract authorized to put messages into this rollup's inbox
* @param _outbox Outbox contract to add
*/
function setOutbox(IOutbox _outbox) external override {
outbox = _outbox;
delayedBridge.setOutbox(address(_outbox), true);
emit OwnerFunctionCalled(0);
}
/**
* @notice Disable an old outbox from interacting with the bridge
* @param _outbox Outbox contract to remove
*/
function removeOldOutbox(address _outbox) external override {
require(_outbox != address(outbox), "CUR_OUTBOX");
delayedBridge.setOutbox(_outbox, false);
emit OwnerFunctionCalled(1);
}
/**
* @notice Enable or disable an inbox contract
* @param _inbox Inbox contract to add or remove
* @param _enabled New status of inbox
*/
function setInbox(address _inbox, bool _enabled) external override {
delayedBridge.setInbox(address(_inbox), _enabled);
emit OwnerFunctionCalled(2);
}
/**
* @notice Pause interaction with the rollup contract
*/
function pause() external override {
_pause();
emit OwnerFunctionCalled(3);
}
/**
* @notice Resume interaction with the rollup contract
*/
function resume() external override {
_unpause();
emit OwnerFunctionCalled(4);
}
/**
* @notice Set the addresses of rollup logic facets called
* @param newAdminFacet address of logic that owner of rollup calls
* @param newUserFacet ddress of logic that user of rollup calls
*/
function setFacets(address newAdminFacet, address newUserFacet) external override {
facets[0] = newAdminFacet;
facets[1] = newUserFacet;
emit OwnerFunctionCalled(5);
}
/**
* @notice Set the addresses of the validator whitelist
* @dev It is expected that both arrays are same length, and validator at
* position i corresponds to the value at position i
* @param _validator addresses to set in the whitelist
* @param _val value to set in the whitelist for corresponding address
*/
function setValidator(address[] memory _validator, bool[] memory _val) external override {
require(_validator.length == _val.length, "WRONG_LENGTH");
for (uint256 i = 0; i < _validator.length; i++) {
isValidator[_validator[i]] = _val[i];
}
emit OwnerFunctionCalled(6);
}
/**
* @notice Set a new owner address for the rollup
* @param newOwner address of new rollup owner
*/
function setOwner(address newOwner) external override {
owner = newOwner;
emit OwnerFunctionCalled(7);
}
/**
* @notice Set minimum assertion period for the rollup
* @param newPeriod new minimum period for assertions
*/
function setMinimumAssertionPeriod(uint256 newPeriod) external override {
minimumAssertionPeriod = newPeriod;
emit OwnerFunctionCalled(8);
}
/**
* @notice Set number of blocks until a node is considered confirmed
* @param newConfirmPeriod new number of blocks
*/
function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external override {
confirmPeriodBlocks = newConfirmPeriod;
emit OwnerFunctionCalled(9);
}
/**
* @notice Set number of extra blocks after a challenge
* @param newExtraTimeBlocks new number of blocks
*/
function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external override {
extraChallengeTimeBlocks = newExtraTimeBlocks;
emit OwnerFunctionCalled(10);
}
/**
* @notice Set speed limit per block
* @param newArbGasSpeedLimitPerBlock maximum arbgas to be used per block
*/
function setArbGasSpeedLimitPerBlock(uint256 newArbGasSpeedLimitPerBlock) external override {
arbGasSpeedLimitPerBlock = newArbGasSpeedLimitPerBlock;
emit OwnerFunctionCalled(11);
}
/**
* @notice Set base stake required for an assertion
* @param newBaseStake maximum arbgas to be used per block
*/
function setBaseStake(uint256 newBaseStake) external override {
baseStake = newBaseStake;
emit OwnerFunctionCalled(12);
}
/**
* @notice Set the token used for stake, where address(0) == eth
* @dev Before changing the base stake token, you might need to change the
* implementation of the Rollup User facet!
* @param newStakeToken address of token used for staking
*/
function setStakeToken(address newStakeToken) external override {
stakeToken = newStakeToken;
emit OwnerFunctionCalled(13);
}
/**
* @notice Set max delay in blocks for sequencer inbox
* @param newSequencerInboxMaxDelayBlocks max number of blocks
*/
function setSequencerInboxMaxDelayBlocks(uint256 newSequencerInboxMaxDelayBlocks)
external
override
{
sequencerInboxMaxDelayBlocks = newSequencerInboxMaxDelayBlocks;
emit OwnerFunctionCalled(14);
}
/**
* @notice Set max delay in seconds for sequencer inbox
* @param newSequencerInboxMaxDelaySeconds max number of seconds
*/
function setSequencerInboxMaxDelaySeconds(uint256 newSequencerInboxMaxDelaySeconds)
external
override
{
sequencerInboxMaxDelaySeconds = newSequencerInboxMaxDelaySeconds;
emit OwnerFunctionCalled(15);
}
/**
* @notice Set execution bisection degree
* @param newChallengeExecutionBisectionDegree execution bisection degree
*/
function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree)
external
override
{
challengeExecutionBisectionDegree = newChallengeExecutionBisectionDegree;
emit OwnerFunctionCalled(16);
}
/**
* @notice Updates a whitelist address for its consumers
* @dev setting the newWhitelist to address(0) disables it for consumers
* @param whitelist old whitelist to be deprecated
* @param newWhitelist new whitelist to be used
* @param targets whitelist consumers to be triggered
*/
function updateWhitelistConsumers(
address whitelist,
address newWhitelist,
address[] memory targets
) external override {
Whitelist(whitelist).triggerConsumers(newWhitelist, targets);
emit OwnerFunctionCalled(17);
}
/**
* @notice Updates a whitelist's entries
* @dev user at position i will be assigned value i
* @param whitelist whitelist to be updated
* @param user users to be updated in the whitelist
* @param val if user is or not allowed in the whitelist
*/
function setWhitelistEntries(
address whitelist,
address[] memory user,
bool[] memory val
) external override {
require(user.length == val.length, "INVALID_INPUT");
Whitelist(whitelist).setWhitelist(user, val);
emit OwnerFunctionCalled(18);
}
/**
* @notice Updates a sequencer address at the sequencer inbox
* @param newSequencer new sequencer address to be used
*/
function setSequencer(address newSequencer) external override {
ISequencerInbox(sequencerBridge).setSequencer(newSequencer);
emit OwnerFunctionCalled(19);
}
/**
* @notice Upgrades the implementation of a beacon controlled by the rollup
* @param beacon address of beacon to be upgraded
* @param newImplementation new address of implementation
*/
function upgradeBeacon(address beacon, address newImplementation) external override {
UpgradeableBeacon(beacon).upgradeTo(newImplementation);
emit OwnerFunctionCalled(20);
}
/*
function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external override whenPaused {
require(stackerA.length == stackerB.length, "WRONG_LENGTH");
for (uint256 i = 0; i < stackerA.length; i++) {
address chall = inChallenge(stackerA[i], stackerB[i]);
require(address(0) != chall, "NOT_IN_CHALL");
clearChallenge(stackerA[i]);
clearChallenge(stackerB[i]);
IChallenge(chall).clearChallenge();
}
}
function forceRefundStaker(address[] memory stacker) external override whenPaused {
for (uint256 i = 0; i < stacker.length; i++) {
withdrawStaker(stacker[i]);
}
}
function forceCreateNode(
bytes32 expectedNodeHash,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 prevNode,
uint256 deadlineBlock,
uint256 sequencerBatchEnd,
bytes32 sequencerBatchAcc
) external override whenPaused {
require(prevNode == latestConfirmed(), "ONLY_LATEST_CONFIRMED");
RollupLib.Assertion memory assertion =
RollupLib.decodeAssertion(
assertionBytes32Fields,
assertionIntFields,
beforeProposedBlock,
beforeInboxMaxCount,
sequencerBridge.messageCount()
);
bytes32 nodeHash =
_newNode(
assertion,
deadlineBlock,
sequencerBatchEnd,
sequencerBatchAcc,
prevNode,
getNodeHash(prevNode),
false
);
// TODO: should we add a stake?
require(expectedNodeHash == nodeHash, "NOT_EXPECTED_HASH");
}
function forceConfirmNode(
bytes calldata sendsData,
uint256[] calldata sendLengths
) external override whenPaused {
outbox.processOutgoingMessages(sendsData, sendLengths);
confirmLatestNode();
rollupEventBridge.nodeConfirmed(latestConfirmed());
// emit NodeConfirmed(
// firstUnresolved,
// afterSendAcc,
// afterSendCount,
// afterLogAcc,
// afterLogCount
// );
}
*/
}
| Functions are only to reach this facet if the caller is the owner so there is no need for a redundant onlyOwner check/ Add a contract authorized to put messages into this rollup's inbox _outbox Outbox contract to add/ | function setOutbox(IOutbox _outbox) external override {
outbox = _outbox;
delayedBridge.setOutbox(address(_outbox), true);
emit OwnerFunctionCalled(0);
}
| 12,870,281 |
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Enjinstarter
pragma solidity ^0.7.6;
pragma abicoder v2; // solhint-disable-line
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/ICrowdsale.sol";
/**
* @title Crowdsale
* @author Enjinstarter
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ERC20 tokens. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard, ICrowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10;
uint256 public constant TOKEN_MAX_DECIMALS = 18;
uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS;
// Amount of tokens sold
uint256 public tokensSold;
// The token being sold
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
address private _tokenSelling;
// Lot size and maximum number of lots for token being sold
LotsInfo private _lotsInfo;
// Payment tokens
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
address[] private _paymentTokens;
// Payment token decimals
// https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar
// slither-disable-next-line similar-names
mapping(address => uint256) private _paymentDecimals;
// Indicates whether ERC20 token is acceptable for payment
mapping(address => bool) private _isPaymentTokens;
// Address where funds are collected
address private _wallet;
// How many weis one token costs for each ERC20 payment token
mapping(address => uint256) private _rates;
// Amount of wei raised for each payment token
mapping(address => uint256) private _weiRaised;
/**
* @dev Rates will denote how many weis one token costs for each ERC20 payment token.
* For USDC or USDT payment token which has 6 decimals, minimum rate will
* be 1000000000000 which will correspond to a price of USD0.000001 per token.
* @param wallet_ Address where collected funds will be forwarded to
* @param tokenSelling_ Address of the token being sold
* @param lotsInfo Lot size and maximum number of lots for token being sold
* @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment
*/
constructor(
address wallet_,
address tokenSelling_,
LotsInfo memory lotsInfo,
PaymentTokenInfo[] memory paymentTokensInfo
) {
require(wallet_ != address(0), "Crowdsale: zero wallet address");
require(
tokenSelling_ != address(0),
"Crowdsale: zero token selling address"
);
require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size");
require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots");
require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens");
require(
paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS,
"Crowdsale: exceed max payment tokens"
);
_wallet = wallet_;
_tokenSelling = tokenSelling_;
_lotsInfo = lotsInfo;
for (uint256 i = 0; i < paymentTokensInfo.length; i++) {
uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal;
require(
paymentDecimal <= TOKEN_MAX_DECIMALS,
"Crowdsale: decimals exceed 18"
);
address paymentToken = paymentTokensInfo[i].paymentToken;
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
uint256 rate_ = paymentTokensInfo[i].rate;
require(rate_ > 0, "Crowdsale: zero rate");
_isPaymentTokens[paymentToken] = true;
_paymentTokens.push(paymentToken);
_paymentDecimals[paymentToken] = paymentDecimal;
_rates[paymentToken] = rate_;
}
}
/**
* @return tokenSelling_ the token being sold
*/
function tokenSelling()
external
view
override
returns (address tokenSelling_)
{
tokenSelling_ = _tokenSelling;
}
/**
* @return wallet_ the address where funds are collected
*/
function wallet() external view override returns (address wallet_) {
wallet_ = _wallet;
}
/**
* @return paymentTokens_ the payment tokens
*/
function paymentTokens()
external
view
override
returns (address[] memory paymentTokens_)
{
paymentTokens_ = _paymentTokens;
}
/**
* @param paymentToken ERC20 payment token address
* @return rate_ how many weis one token costs for specified ERC20 payment token
*/
function rate(address paymentToken)
external
view
override
returns (uint256 rate_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
rate_ = _rate(paymentToken);
}
/**
* @return lotSize_ lot size of token being sold
*/
function lotSize() public view override returns (uint256 lotSize_) {
lotSize_ = _lotsInfo.lotSize;
}
/**
* @return maxLots_ maximum number of lots for token being sold
*/
function maxLots() external view override returns (uint256 maxLots_) {
maxLots_ = _lotsInfo.maxLots;
}
/**
* @param paymentToken ERC20 payment token address
* @return weiRaised_ the amount of wei raised
*/
function weiRaisedFor(address paymentToken)
external
view
override
returns (uint256 weiRaised_)
{
weiRaised_ = _weiRaisedFor(paymentToken);
}
/**
* @param paymentToken ERC20 payment token address
* @return isPaymentToken_ whether token is accepted for payment
*/
function isPaymentToken(address paymentToken)
public
view
override
returns (bool isPaymentToken_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
isPaymentToken_ = _isPaymentTokens[paymentToken];
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @return tokenAmount Number of tokens being sold that will be purchased
*/
function getTokenAmount(uint256 lots)
external
view
override
returns (uint256 tokenAmount)
{
require(lots > 0, "Crowdsale: zero lots");
tokenAmount = _getTokenAmount(lots);
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
* @return weiAmount Amount in wei of ERC20 payment token
*/
function getWeiAmount(address paymentToken, uint256 lots)
external
view
override
returns (uint256 weiAmount)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiAmount = _getWeiAmount(paymentToken, lots);
}
/**
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function buyTokens(address paymentToken, uint256 lots) external override {
_buyTokensFor(msg.sender, paymentToken, lots);
}
/**
* @param beneficiary Recipient of the token purchase
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) external override {
_buyTokensFor(beneficiary, paymentToken, lots);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
function _buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) internal nonReentrant {
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
// calculate token amount to be created
uint256 tokenAmount = _getTokenAmount(lots);
// calculate wei amount to transfer to wallet
uint256 weiAmount = _getWeiAmount(paymentToken, lots);
_preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount);
// update state
_weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
_updatePurchasingState(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
emit TokensPurchased(
msg.sender,
beneficiary,
paymentToken,
lots,
weiAmount,
tokenAmount
);
_processPurchase(beneficiary, tokenAmount);
_forwardFunds(paymentToken, weiAmount);
_postValidatePurchase(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
}
/**
* @param paymentToken ERC20 payment token address
* @return weiRaised_ the amount of wei raised
*/
function _weiRaisedFor(address paymentToken)
internal
view
virtual
returns (uint256 weiRaised_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiRaised_ = _weiRaised[paymentToken];
}
/**
* @param paymentToken ERC20 payment token address
* @return rate_ how many weis one token costs for specified ERC20 payment token
*/
function _rate(address paymentToken)
internal
view
virtual
returns (uint256 rate_)
{
rate_ = _rates[paymentToken];
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _preValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo/rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _postValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
// https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
// slither-disable-next-line dead-code
function _deliverTokens(address beneficiary, uint256 tokenAmount)
internal
virtual
{
IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount)
internal
virtual
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount in wei of ERC20 payment token
* @param tokenAmount Number of tokens to be purchased
*/
function _updatePurchasingState(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @return tokenAmount Number of tokens that will be purchased
*/
function _getTokenAmount(uint256 lots)
internal
view
virtual
returns (uint256 tokenAmount)
{
tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE);
}
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
* @return weiAmount Amount in wei of ERC20 payment token
*/
function _getWeiAmount(address paymentToken, uint256 lots)
internal
view
virtual
returns (uint256 weiAmount)
{
uint256 rate_ = _rate(paymentToken);
uint256 tokenAmount = _getTokenAmount(lots);
weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE);
}
/**
* @dev Determines how ERC20 payment token is stored/forwarded on purchases.
*/
function _forwardFunds(address paymentToken, uint256 weiAmount)
internal
virtual
{
uint256 amount = weiAmount;
if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) {
uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub(
_paymentDecimals[paymentToken]
);
amount = weiAmount.div(10**decimalsDiff);
}
IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount);
}
}
| return wallet_ the address where funds are collected/ | function wallet() external view override returns (address wallet_) {
wallet_ = _wallet;
}
| 6,367,986 |
pragma solidity ^0.5.0;
/* Oh wow, it's finally happening /*
╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
║ $$$$$$$\ $$\ $$\ $$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$$\ ║
║ $$ __$$\ $$ | $\ $$ |$$ | $$ | $$ ___$$\ $$ __$$\ $$ _____| ║
║ $$ | $$ | $$$$$$\ $$ |$$$\ $$ |$$ | $$ | \_/ $$ |$$ | $$ | $$ | $$\ $$\ ║
║ $$$$$$$ |$$ __$$\ $$ $$ $$\$$ |$$$$$$$$ | $$$$$ / $$ | $$ | $$$$$\ \$$\ $$ | ║
║ $$ ____/ $$ / $$ |$$$$ _$$$$ |$$ __$$ | \___$$\ $$ | $$ | $$ __| \$$$$ / ║
║ $$ | $$ | $$ |$$$ / \$$$ |$$ | $$ | $$\ $$ |$$ | $$ | $$ | $$ $$< ║
║ $$ | \$$$$$$ |$$ / \$$ |$$ | $$ | \$$$$$$ |$$$$$$$ | $$$$$$$$\ $$ /\$$\ ║
║ \__| \______/ \__/ \__|\__| \__| \______/ \_______/ \________|\__/ \__| ║
║ ║
╠══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
║ _____ __ __ __ __ _ _ _ _ ║
║ | __ \ / _| / _| \ \ / / | | | | | | | | ║
║ | |__) | __ ___ ___ | |_ ___ | |_ \ \ /\ / /__ __ _| | __ | |__| | __ _ _ __ __| |___ ║
║ | ___/ '__/ _ \ / _ \| _| / _ \| _| \ \/ \/ / _ \/ _` | |/ / | __ |/ _` | '_ \ / _` / __| ║
║ | | | | | (_) | (_) | | | (_) | | \ /\ / __/ (_| | < | | | | (_| | | | | (_| \__ \ ║
║ |_| |_| \___/ \___/|_| \___/|_| \/ \/ \___|\__,_|_|\_\ |_| |_|\__,_|_| |_|\__,_|___/ ║
║ ____ _____ ________ _________ ______ _ _ _____ ______ _____ ║
║ |___ \| __ \ _ | ____\ \ / /__ __| ____| \ | | __ \| ____| __ \ ║
║ __) | | | | (_) | |__ \ V / | | | |__ | \| | | | | |__ | | | | ║
║ |__ <| | | | | __| > < | | | __| | . ` | | | | __| | | | | ║
║ ___) | |__| | _ | |____ / . \ | | | |____| |\ | |__| | |____| |__| | ║
║ |____/|_____/ (_) |______/_/ \_\ |_| |______|_| \_|_____/|______|_____/ ║
║ ╔══════════════════════════╗ ║
╚═════════════════════════════════════════════╣ Created by ARitz Cracker ╠═════════════════════════════════════════════╝
╚══════════════════════════╝
In a world, where people wanted more 3rd party dApp integration with P3D, a small "Jack of all trades" developer,
ARitz Cracker set out to create an addon-token for P3D that would add the functionality required for 3rd party dApp
integration. However, while creating this, he had another calling... Replacing web3js and Metamask a grand feat, for
sure. Unfortunately, this left the extension token aside. One man took advantage of this functionality-vacuum and
created his own extension, but it was forged by greed... and would force its users to pay additional fees and taxes to
the creator and anyone he saw fit. ARitz Cracker saw this as a sign... "People need community focused dApp extensions
now!" And so, he set out to have it completed, audited, and ready for the community as soon as possible... In order to
prevent the greedy ones from taking power away from the community.
Thus, P3X was born.
So, what does this thing actually do?
* P3X is a utility token tethered to P3D.
* The total P3X supply will always be equal to the amount of P3D bought by this contract.
* P3X Price will always be equal to P3D price
* Dividends per P3X token is the same as P3D
* Functionally identical to P3D Exept:
* 0% token fees on transfers
* Full ERC20 and ERC223 functionality, allowing for external dApps to _actually_ receive funds and interact with the contract.
* Optional gauntlets which prevent you from selling (literally!)
* For more information, please visit the wiki page: https://powh3d.hostedwiki.co/pages/What%20is%20P3X
Also, this is my first contract on main-net please be gentle :S
*/
// Interfaces for easy copypasta
interface ERC20interface {
function transfer(address to, uint value) external returns(bool success);
function approve(address spender, uint tokens) external returns(bool success);
function transferFrom(address from, address to, uint tokens) external returns(bool success);
function allowance(address tokenOwner, address spender) external view returns(uint remaining);
function balanceOf(address tokenOwner) external view returns(uint balance);
}
interface ERC223interface {
function transfer(address to, uint value) external returns(bool ok);
function transfer(address to, uint value, bytes calldata data) external returns(bool ok);
function transfer(address to, uint value, bytes calldata data, string calldata customFallback) external returns(bool ok);
function balanceOf(address who) external view returns(uint);
}
// If your contract wants to accept P3X, implement this function
interface ERC223Handler {
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
// External gauntlet interfaces can be useful for something like voting systems or contests
interface ExternalGauntletInterface {
function gauntletRequirement(address wearer, uint256 oldAmount, uint256 newAmount) external returns(bool);
function gauntletRemovable(address wearer) external view returns(bool);
}
// This is P3D itself (not a cimplete interface)
interface Hourglass {
function decimals() external view returns(uint8);
function stakingRequirement() external view returns(uint256);
function balanceOf(address tokenOwner) external view returns(uint);
function dividendsOf(address tokenOwner) external view returns(uint);
function calculateTokensReceived(uint256 _ethereumToSpend) external view returns(uint256);
function calculateEthereumReceived(uint256 _tokensToSell) external view returns(uint256);
function myTokens() external view returns(uint256);
function myDividends(bool _includeReferralBonus) external view returns(uint256);
function totalSupply() external view returns(uint256);
function transfer(address to, uint value) external returns(bool);
function buy(address referrer) external payable returns(uint256);
function sell(uint256 amount) external;
function withdraw() external;
}
// This a name database used in Fomo3D (Also not a complete interface)
interface TeamJustPlayerBook {
function pIDxName_(bytes32 name) external view returns(uint256);
function pIDxAddr_(address addr) external view returns(uint256);
function getPlayerAddr(uint256 pID) external view returns(address);
}
// Here's an interface in case you want to integration your dApp with this.
// Descriptions of each function are down below in the soure code.
// NOTE: It's not _entirely_ compatible with the P3D interface. myTokens() has been renamed to myBalance().
/*
interface HourglassX {
function buy(address referrerAddress) payable external returns(uint256 tokensReceieved);
function buy(string calldata referrerName) payable external returns(uint256 tokensReceieved);
function reinvest() external returns(uint256 tokensReceieved);
function reinvestPartial(uint256 ethToReinvest) external returns(uint256 tokensReceieved);
function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) external returns(uint256 tokensReceieved);
function sell(uint256 amount, bool withdrawAfter) external returns(uint256 ethReceieved);
function sell(uint256 amount) external returns(uint256 ethReceieved); // Alias of sell(amount, false)
function withdraw() external;
function exit() external;
function acquireGauntlet(uint256 amount, uint8 gType, uint256 end) external;
function acquireExternalGauntlet(uint256 amount, address extGauntlet) external;
function setReferrer(address referrer) external;
function setReferrer(string calldata referrerName) external;
function myBalance() external view returns(uint256 balance);
function dividendsOf(address accountHolder, bool includeReferralBonus) external view returns(uint256 divs);
function dividendsOf(address accountHolder) external view returns(uint256 divs); // Alias of dividendsOf(accountHolder, true)
function myDividends(bool includeReferralBonus) external view returns(uint256 divs);
function myDividends() external view returns(uint256 divs); // Alias of myDividends(true);
function usableBalanceOf(address accountHolder) external view returns(uint256 balance);
function myUsableBalance() external view returns(uint256 balance);
function refBonusOf(address customerAddress) external view returns(uint256);
function myRefBonus() external view returns(uint256);
function gauntletTypeOf(address accountHolder) external view returns(uint256 stakeAmount, uint256 gType, uint256 end);
function myGauntletType() external view returns(uint256 stakeAmount, uint256 gType, uint256 end);
function stakingRequirement() external view returns(uint256);
function savedReferral(address accountHolder) external view returns(address);
// ERC 20/223
function balanceOf(address tokenOwner) external view returns(uint balance);
function transfer(address to, uint value) external returns(bool ok);
function transfer(address to, uint value, bytes data) external returns(bool ok);
function transfer(address to, uint value, bytes data, string customFallback) external returns(bool ok);
function allowance(address tokenOwner, address spender) external view returns(uint remaining);
function approve(address spender, uint tokens) external returns(bool success);
function transferFrom(address from, address to, uint tokens) external returns(bool success);
// Events (cannot be in interfaces used here as a reference)
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint value);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
event onTokenPurchase(
address indexed accountHolder,
uint256 ethereumSpent,
uint256 tokensCreated,
uint256 tokensGiven,
address indexed referrer,
uint8 bitFlags // 1 = invalidMasternode, 2 = usedHourglassMasternode, 4 = reinvestment
);
event onTokenSell(
address indexed accountHolder,
uint256 tokensDestroyed,
uint256 ethereumEarned
);
event onWithdraw(
address indexed accountHolder,
uint256 earningsWithdrawn,
uint256 refBonusWithdrawn,
bool reinvestment
);
event onDonatedDividends(
address indexed donator,
uint256 ethereumDonated
);
event onGauntletAcquired(
address indexed strongHands,
uint256 stakeAmount,
uint8 gauntletType,
uint256 end
);
event onExternalGauntletAcquired(
address indexed strongHands,
uint256 stakeAmount,
address indexed extGauntlet
);
// Gauntlet events will be emitted with stakeAmount == 0 when the gauntlets expire.
}
*/
// This contract is intended to only be used by HourglassX. Think of this as HourglassX's second account (or child slave with its own account)
contract HourglassXReferralHandler {
using SafeMath for uint256;
using SafeMath for uint;
address internal parent;
Hourglass internal hourglass;
constructor(Hourglass h) public {
hourglass = h;
parent = msg.sender;
}
// Don't expose this account to literally everyone
modifier onlyParent {
require(msg.sender == parent, "Can only be executed by parent process");
_;
}
// Contract's total ETH balance including divs
function totalBalance() public view returns(uint256) {
return address(this).balance + hourglass.myDividends(true);
}
// Buy P3D from given ether
function buyTokens(address referrer) public payable onlyParent {
hourglass.buy.value(msg.value)(referrer);
}
// Buy P3D from own ether balance
function buyTokensFromBalance(address referrer, uint256 amount) public onlyParent {
if (address(this).balance < amount) {
hourglass.withdraw();
}
hourglass.buy.value(amount)(referrer);
}
// Sell a specified amount of P3D for ether
function sellTokens(uint256 amount) public onlyParent {
if (amount > 0) {
hourglass.sell(amount);
}
}
// Withdraw outstanding divs to internal balance
function withdrawDivs() public onlyParent {
hourglass.withdraw();
}
// Send eth from internal balance to a specified account
function sendETH(address payable to, uint256 amount) public onlyParent {
if (address(this).balance < amount) {
hourglass.withdraw();
}
to.transfer(amount);
}
// Only allow ETH from our master or from the hourglass.
function() payable external {
require(msg.sender == address(hourglass) || msg.sender == parent, "No, I don't accept donations");
}
// Reject possible accidental sendin of higher-tech shitcoins.
function tokenFallback(address from, uint value, bytes memory data) public pure {
revert("I don't want your shitcoins!");
}
// Allow anyone else to take forcefully sent low-tech shitcoins. (I sure as hell don't want them)
function takeShitcoin(address shitCoin) public {
require(shitCoin != address(hourglass), "P3D isn't a shitcoin");
ERC20interface s = ERC20interface(shitCoin);
s.transfer(msg.sender, s.balanceOf(address(this)));
}
}
contract HourglassX {
using SafeMath for uint256;
using SafeMath for uint;
using SafeMath for int256;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier playerBookEnabled {
require(address(playerBook) != NULL_ADDRESS, "named referrals not enabled");
_;
}
// Make the thing
constructor(address h, address p) public {
// Set up ERC20 values
name = "PoWH3D Extended";
symbol = "P3X";
decimals = 18;
totalSupply = 0;
// Add external contracts
hourglass = Hourglass(h);
playerBook = TeamJustPlayerBook(p);
// Set referral requirement to be the same as P3D by default.
referralRequirement = hourglass.stakingRequirement();
// Yes I could deploy 2 contracts myself, but I'm lazy. :^)
refHandler = new HourglassXReferralHandler(hourglass);
// Internal stuffs
ignoreTokenFallbackEnable = false;
owner = msg.sender;
}
// HourglassX-specific data
address owner;
address newOwner;
uint256 referralRequirement;
uint256 internal profitPerShare = 0;
uint256 public lastTotalBalance = 0;
uint256 constant internal ROUNDING_MAGNITUDE = 2**64;
address constant internal NULL_ADDRESS = 0x0000000000000000000000000000000000000000;
// I would get this from hourglass, but these values are inaccessable to the public.
uint8 constant internal HOURGLASS_FEE = 10;
uint8 constant internal HOURGLASS_BONUS = 3;
// External contracts
Hourglass internal hourglass;
HourglassXReferralHandler internal refHandler;
TeamJustPlayerBook internal playerBook;
// P3X Specific data
mapping(address => int256) internal payouts;
mapping(address => uint256) internal bonuses;
mapping(address => address) public savedReferral;
// Futureproofing stuffs
mapping(address => mapping (address => bool)) internal ignoreTokenFallbackList;
bool internal ignoreTokenFallbackEnable;
// Gauntlets
mapping(address => uint256) internal gauntletBalance;
mapping(address => uint256) internal gauntletEnd;
mapping(address => uint8) internal gauntletType; // 1 = Time, 2 = P3D Supply, 3 = External
// Normal token data
mapping(address => uint256) internal balances;
mapping(address => mapping (address => uint256)) internal allowances;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// --Events
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint value);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
// Q: Why do you have 2 transfer events?
// A: Because keccak256("Transfer(address,address,uint256)") != keccak256("Transfer(address,address,uint256,bytes)")
// and etherscan listens for the former.
event onTokenPurchase(
address indexed accountHolder,
uint256 ethereumSpent,
uint256 tokensCreated,
// If P3D is given to the contract, that amount in P3X will be given to the next buyer since we have no idea who gave us the P3D.
uint256 tokensGiven,
address indexed referrer,
uint8 indexed bitFlags // 1 = invalidMasternode, 2 = usedHourglassMasternode, 4 = reinvestment
);
event onTokenSell(
address indexed accountHolder,
uint256 tokensDestroyed,
uint256 ethereumEarned
);
event onWithdraw(
address indexed accountHolder,
uint256 earningsWithdrawn,
uint256 refBonusWithdrawn,
bool indexed reinvestment
);
event onDonatedDividends(
address indexed donator,
uint256 ethereumDonated
);
event onGauntletAcquired(
address indexed strongHands,
uint256 stakeAmount,
uint8 indexed gauntletType,
uint256 end
);
event onExternalGauntletAcquired(
address indexed strongHands,
uint256 stakeAmount,
address indexed extGauntlet
);
// --Events--
// --Owner only functions
function setNewOwner(address o) public onlyOwner {
newOwner = o;
}
function acceptNewOwner() public {
require(msg.sender == newOwner);
owner = msg.sender;
}
// P3D allows re-branding, makes sense if P3X allows it too.
function rebrand(string memory n, string memory s) public onlyOwner {
name = n;
symbol = s;
}
// P3X selling point: _lower staking requirement than P3D!!_
function setReferralRequirement(uint256 r) public onlyOwner {
referralRequirement = r;
}
// Enables the function defined below.
function allowIgnoreTokenFallback() public onlyOwner {
ignoreTokenFallbackEnable = true;
}
// --Owner only functions--
// --Public write functions
// Ethereum _might_ implement something where every address, including ones controlled by humans, is a smart contract.
// Obviously transfering P3X to other people with no fee is one of its selling points.
// A somewhat future-proofing fix is for the sender to specify that their recipiant is human if such a change ever takes place.
// However, due to the popularity of ERC223, this might not be necessary.
function ignoreTokenFallback(address to, bool ignore) public {
require(ignoreTokenFallbackEnable, "This function is disabled");
ignoreTokenFallbackList[msg.sender][to] = ignore;
}
// Transfer tokens to the specified address, call the specified function, and pass the specified data
function transfer(address payable to, uint value, bytes memory data, string memory func) public returns(bool) {
actualTransfer(msg.sender, to, value, data, func, true);
return true;
}
// Transfer tokens to the specified address, call tokenFallback, and pass the specified data
function transfer(address payable to, uint value, bytes memory data) public returns(bool) {
actualTransfer(msg.sender, to, value, data, "", true);
return true;
}
// Transfer tokens to the specified address, call tokenFallback if applicable
function transfer(address payable to, uint value) public returns(bool) {
actualTransfer(msg.sender, to, value, "", "", !ignoreTokenFallbackList[msg.sender][to]);
return true;
}
// Allow someone else to spend your tokens
function approve(address spender, uint value) public returns(bool) {
require(updateUsableBalanceOf(msg.sender) >= value, "Insufficient balance to approve");
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
// Have that someone else spend your tokens
function transferFrom(address payable from, address payable to, uint value) public returns(bool success) {
uint256 allowance = allowances[from][msg.sender];
require(allowance > 0, "Not approved");
require(allowance >= value, "Over spending limit");
allowances[from][msg.sender] = allowance.sub(value);
actualTransfer(from, to, value, "", "", false);
return true;
}
// The fallback function
function() payable external{
// Only accept free ETH from the hourglass and from our child slave.
if (msg.sender != address(hourglass) && msg.sender != address(refHandler)) {
// Now, sending ETH increases the balance _before_ the transaction has been fully processed.
// We don't want to distribute the entire purchase order as dividends.
if (msg.value > 0) {
lastTotalBalance += msg.value;
distributeDividends(0, NULL_ADDRESS);
lastTotalBalance -= msg.value;
}
createTokens(msg.sender, msg.value, NULL_ADDRESS, false);
}
}
// Worried about having weak hands? Put on an optional gauntlet.
// Prevents you from selling or transfering a specified amount of tokens
function acquireGauntlet(uint256 amount, uint8 gType, uint256 end) public{
require(amount <= balances[msg.sender], "Insufficient balance");
// We need to apply the data first in order to prevent re-entry attacks.
// ExternalGauntletInterface.gauntletRequirement _is_ a function which can change the state, after all.
uint256 oldGauntletType = gauntletType[msg.sender];
uint256 oldGauntletBalance = gauntletBalance[msg.sender];
uint256 oldGauntletEnd = gauntletEnd[msg.sender];
gauntletType[msg.sender] = gType;
gauntletEnd[msg.sender] = end;
gauntletBalance[msg.sender] = amount;
if (oldGauntletType == 0) {
if (gType == 1) {
require(end >= (block.timestamp + 97200), "Gauntlet time must be >= 4 weeks"); //97200 seconds = 3 weeks and 6 days.
emit onGauntletAcquired(msg.sender, amount, gType, end);
} else if (gType == 2) {
uint256 P3DSupply = hourglass.totalSupply();
require(end >= (P3DSupply + (P3DSupply / 5)), "Gauntlet must make a profit"); // P3D buyers are down 19% when they buy, so make gauntlet gainz a minimum of 20%.
emit onGauntletAcquired(msg.sender, amount, gType, end);
} else if (gType == 3) {
require(end <= 0x00ffffffffffffffffffffffffffffffffffffffff, "Invalid address");
require(ExternalGauntletInterface(address(end)).gauntletRequirement(msg.sender, 0, amount), "External gauntlet check failed");
emit onExternalGauntletAcquired(msg.sender, amount, address(end));
} else {
revert("Invalid gauntlet type");
}
} else if (oldGauntletType == 3) {
require(gType == 3, "New gauntlet must be same type");
require(end == gauntletEnd[msg.sender], "Must be same external gauntlet");
require(ExternalGauntletInterface(address(end)).gauntletRequirement(msg.sender, oldGauntletBalance, amount), "External gauntlet check failed");
emit onExternalGauntletAcquired(msg.sender, amount, address(end));
} else {
require(gType == oldGauntletType, "New gauntlet must be same type");
require(end > oldGauntletEnd, "Gauntlet must be an upgrade");
require(amount >= oldGauntletBalance, "New gauntlet must hold more tokens");
emit onGauntletAcquired(msg.sender, amount, gType, end);
}
}
function acquireExternalGauntlet(uint256 amount, address extGauntlet) public{
acquireGauntlet(amount, 3, uint256(extGauntlet));
}
// Throw your money at this thing with a referrer specified by their Ethereum address.
// Returns the amount of tokens created.
function buy(address referrerAddress) payable public returns(uint256) {
// Now, sending ETH increases the balance _before_ the transaction has been fully processed.
// We don't want to distribute the entire purchase order as dividends.
if (msg.value > 0) {
lastTotalBalance += msg.value;
distributeDividends(0, NULL_ADDRESS);
lastTotalBalance -= msg.value;
}
return createTokens(msg.sender, msg.value, referrerAddress, false);
}
// I'm only copy/pasting these functions due to the stack limit.
// Throw your money at this thing with a referrer specified by their team JUST playerbook name.
// Returns the amount of tokens created.
function buy(string memory referrerName) payable public playerBookEnabled returns(uint256) {
address referrerAddress = getAddressFromReferralName(referrerName);
// As I said before, we don't want to distribute the entire purchase order as dividends.
if (msg.value > 0) {
lastTotalBalance += msg.value;
distributeDividends(0, NULL_ADDRESS);
lastTotalBalance -= msg.value;
}
return createTokens(msg.sender, msg.value, referrerAddress, false);
}
// Use all the ETH you earned hodling P3X to buy more P3X.
// Returns the amount of tokens created.
function reinvest() public returns(uint256) {
address accountHolder = msg.sender;
distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened.
uint256 payout;
uint256 bonusPayout;
(payout, bonusPayout) = clearDividends(accountHolder);
emit onWithdraw(accountHolder, payout, bonusPayout, true);
return createTokens(accountHolder, payout + bonusPayout, NULL_ADDRESS, true);
}
// Use some of the ETH you earned hodling P3X to buy more P3X.
// You can withdraw the rest or keept it in here allocated for you.
// Returns the amount of tokens created.
function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) public returns(uint256 tokensCreated) {
address payable accountHolder = msg.sender;
distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened.
uint256 payout = dividendsOf(accountHolder, false);
uint256 bonusPayout = bonuses[accountHolder];
uint256 payoutReinvested = 0;
uint256 bonusReinvested;
require((payout + bonusPayout) >= ethToReinvest, "Insufficient balance for reinvestment");
// We're going to take ETH out of the masternode bonus first, then the outstanding divs.
if (ethToReinvest > bonusPayout){
payoutReinvested = ethToReinvest - bonusPayout;
bonusReinvested = bonusPayout;
// Take ETH out from outstanding dividends.
payouts[accountHolder] += int256(payoutReinvested * ROUNDING_MAGNITUDE);
}else{
bonusReinvested = ethToReinvest;
}
// Take ETH from the masternode bonus.
bonuses[accountHolder] -= bonusReinvested;
emit onWithdraw(accountHolder, payoutReinvested, bonusReinvested, true);
// Do the buy thing!
tokensCreated = createTokens(accountHolder, ethToReinvest, NULL_ADDRESS, true);
if (withdrawAfter && dividendsOf(msg.sender, true) > 0) {
withdrawDividends(msg.sender);
}
return tokensCreated;
}
// I'm just a man who loves "default variables"
function reinvestPartial(uint256 ethToReinvest) public returns(uint256) {
return reinvestPartial(ethToReinvest, true);
}
// There's literally no reason to call this function
function sell(uint256 amount, bool withdrawAfter) public returns(uint256) {
require(amount > 0, "You have to sell something");
uint256 sellAmount = destroyTokens(msg.sender, amount);
if (withdrawAfter && dividendsOf(msg.sender, true) > 0) {
withdrawDividends(msg.sender);
}
return sellAmount;
}
// Again with the default variables!
function sell(uint256 amount) public returns(uint256) {
require(amount > 0, "You have to sell something");
return destroyTokens(msg.sender, amount);
}
// Transfer the sender's masternode bonuses and their outstanding divs to their wallet.
function withdraw() public{
require(dividendsOf(msg.sender, true) > 0, "No dividends to withdraw");
withdrawDividends(msg.sender);
}
// There's definitely no reason to call this function
function exit() public{
address payable accountHolder = msg.sender;
uint256 balance = balances[accountHolder];
if (balance > 0) {
destroyTokens(accountHolder, balance);
}
if (dividendsOf(accountHolder, true) > 0) {
withdrawDividends(accountHolder);
}
}
// Since website won't be released on launch, provide something on etherscan which will allow users to easily set masternodes.
function setReferrer(address ref) public{
savedReferral[msg.sender] = ref;
}
// Same as above except using the team JUST player book
function setReferrer(string memory refName) public{
savedReferral[msg.sender] = getAddressFromReferralName(refName);
}
// Another P3X selling point: Get P3X-exclusive didvidends _combined with_ P3D dividends!
function donateDividends() payable public{
distributeDividends(0, NULL_ADDRESS);
emit onDonatedDividends(msg.sender, msg.value);
}
// --Public write functions--
// --Public read-only functions
// Returns the P3D address.
function baseHourglass() external view returns(address) {
return address(hourglass);
}
// Returns the salve account address (was mostly used for debugging purposes)
function refHandlerAddress() external view returns(address) {
return address(refHandler);
}
// Get someone's address from their team JUST playerbook name
function getAddressFromReferralName(string memory refName) public view returns (address){
return playerBook.getPlayerAddr(playerBook.pIDxName_(stringToBytes32(refName)));
}
// Retruns an addresses gauntlet type.
function gauntletTypeOf(address accountHolder) public view returns(uint stakeAmount, uint gType, uint end) {
if (isGauntletExpired(accountHolder)) {
return (0, 0, gauntletEnd[accountHolder]);
} else {
return (gauntletBalance[accountHolder], gauntletType[accountHolder], gauntletEnd[accountHolder]);
}
}
// Same as above except for msg.sender
function myGauntletType() public view returns(uint stakeAmount, uint gType, uint end) {
return gauntletTypeOf(msg.sender);
}
// Returns an addresse's P3X balance minus what they have in their gauntlet.
function usableBalanceOf(address accountHolder) public view returns(uint balance) {
if (isGauntletExpired(accountHolder)) {
return balances[accountHolder];
} else {
return balances[accountHolder].sub(gauntletBalance[accountHolder]);
}
}
// Same as above except for msg.sender
function myUsableBalance() public view returns(uint balance) {
return usableBalanceOf(msg.sender);
}
// I mean, every ERC20 token has this function. I'm sure you know what it does.
function balanceOf(address accountHolder) external view returns(uint balance) {
return balances[accountHolder];
}
// Same as above except for msg.sender
function myBalance() public view returns(uint256) {
return balances[msg.sender];
}
// See if the specified sugardaddy allows the spender to spend their tokens
function allowance(address sugardaddy, address spender) external view returns(uint remaining) {
return allowances[sugardaddy][spender];
}
// Returns all the ETH that this contract has access to
function totalBalance() public view returns(uint256) {
return address(this).balance + hourglass.myDividends(true) + refHandler.totalBalance();
}
// Returns the ETH the specified address is owed.
function dividendsOf(address customerAddress, bool includeReferralBonus) public view returns(uint256) {
uint256 divs = uint256(int256(profitPerShare * balances[customerAddress]) - payouts[customerAddress]) / ROUNDING_MAGNITUDE;
if (includeReferralBonus) {
divs += bonuses[customerAddress];
}
return divs;
}
// Same as above except includes the masternode bonus
function dividendsOf(address customerAddress) public view returns(uint256) {
return dividendsOf(customerAddress, true);
}
// Alias of dividendsOf(msg.sender)
function myDividends() public view returns(uint256) {
return dividendsOf(msg.sender, true);
}
// Alias of dividendsOf(msg.sender, includeReferralBonus)
function myDividends(bool includeReferralBonus) public view returns(uint256) {
return dividendsOf(msg.sender, includeReferralBonus);
}
// Returns the masternode earnings of a specified account
function refBonusOf(address customerAddress) external view returns(uint256) {
return bonuses[customerAddress];
}
// Same as above xcept with msg.sender
function myRefBonus() external view returns(uint256) {
return bonuses[msg.sender];
}
// Backwards compatibility with the P3D interface
function stakingRequirement() external view returns(uint256) {
return referralRequirement;
}
// Backwards compatibility with the P3D interface
function calculateTokensReceived(uint256 ethereumToSpend) public view returns(uint256) {
return hourglass.calculateTokensReceived(ethereumToSpend);
}
// Backwards compatibility with the P3D interface
function calculateEthereumReceived(uint256 tokensToSell) public view returns(uint256) {
return hourglass.calculateEthereumReceived(tokensToSell);
}
// --Public read-only functions--
// Internal functions
// Returns true if the gauntlet has expired. Otherwise, false.
function isGauntletExpired(address holder) internal view returns(bool) {
if (gauntletType[holder] != 0) {
if (gauntletType[holder] == 1) {
return (block.timestamp >= gauntletEnd[holder]);
} else if (gauntletType[holder] == 2) {
return (hourglass.totalSupply() >= gauntletEnd[holder]);
} else if (gauntletType[holder] == 3) {
return ExternalGauntletInterface(gauntletEnd[holder]).gauntletRemovable(holder);
}
}
return false;
}
// Same as usableBalanceOf, except the gauntlet is lifted when it's expired.
function updateUsableBalanceOf(address holder) internal returns(uint256) {
// isGauntletExpired is a _view_ function, with uses STATICCALL in solidity 0.5.0 or later.
// Since STATICCALLs can't modifiy the state, re-entry attacks aren't possible here.
if (isGauntletExpired(holder)) {
if (gauntletType[holder] == 3){
emit onExternalGauntletAcquired(holder, 0, NULL_ADDRESS);
}else{
emit onGauntletAcquired(holder, 0, 0, 0);
}
gauntletType[holder] = 0;
gauntletBalance[holder] = 0;
return balances[holder];
}
return balances[holder] - gauntletBalance[holder];
}
// This is the actual buy function
function createTokens(address creator, uint256 eth, address referrer, bool reinvestment) internal returns(uint256) {
// Let's not call the parent hourglass all the time.
uint256 parentReferralRequirement = hourglass.stakingRequirement();
// How much ETH will be given to the referrer if there is one.
uint256 referralBonus = eth / HOURGLASS_FEE / HOURGLASS_BONUS;
bool usedHourglassMasternode = false;
bool invalidMasternode = false;
if (referrer == NULL_ADDRESS) {
referrer = savedReferral[creator];
}
// Solidity has limited amount of local variables, so the memory allocated to this one gets reused for other purposes later.
//uint256 refHandlerBalance = hourglass.balanceOf(address(refHandler));
uint256 tmp = hourglass.balanceOf(address(refHandler));
// Let's once again pretend this actually prevents people from cheating.
if (creator == referrer) {
// Tell everyone that no referral purchase was made because cheating (unlike P3D)
invalidMasternode = true;
} else if (referrer == NULL_ADDRESS) {
usedHourglassMasternode = true;
// Make sure that the referrer has enough funds to _be_ a referrer, and make sure that we have our own P3D masternode to get that extra ETH
} else if (balances[referrer] >= referralRequirement && (tmp >= parentReferralRequirement || hourglass.balanceOf(address(this)) >= parentReferralRequirement)) {
// It's a valid P3X masternode, hooray! (do nothing)
} else if (hourglass.balanceOf(referrer) >= parentReferralRequirement) {
usedHourglassMasternode = true;
} else {
// Tell everyone that no referral purchase was made because not enough balance (again, unlike P3D)
invalidMasternode = true;
}
// Thanks to Crypto McPump for helping me _not_ waste gas here.
/*
uint256 createdTokens = hourglass.calculateTokensReceived(eth); // See? Look how much gas I would have wasted.
totalSupply += createdTokens;
*/
uint256 createdTokens = hourglass.totalSupply();
// KNOWN BUG: If lord Justo increases the staking requirement to something above both of the contract's P3D
// balance, then all masternodes won't work until there are enough buy orders to make the refHandler's P3D
// balance above P3D's masternode requirement.
// if the refHandler hass less P3D than P3D's masternode requirement, then it should buy the tokens.
if (tmp < parentReferralRequirement) {
if (reinvestment) {
// We need to know if the refHandler has enough ETH to do the reinvestment on its own
//uint256 refHandlerEthBalance = refHandler.totalBalance();
tmp = refHandler.totalBalance();
if (tmp < eth) {
// If it doesn't, then we must transfer it the remaining ETH it needs.
tmp = eth - tmp; // fundsToGive = eth - refHandlerEthBalance;
if (address(this).balance < tmp) {
// If this fails, something went horribly wrong because the client is attempting to reinvest more ethereum than we've got
hourglass.withdraw();
}
address(refHandler).transfer(tmp);
}
tmp = hourglass.balanceOf(address(refHandler));
// Reinvestments are always done using the null referrer
refHandler.buyTokensFromBalance(NULL_ADDRESS, eth);
} else {
// these nested ? statements are only here because I can only have a limited amount of local variables.
// Forward the ETH we were sent to the refHandler to place the buy order.
refHandler.buyTokens.value(eth)(invalidMasternode ? NULL_ADDRESS : (usedHourglassMasternode ? referrer : address(this)));
}
} else {
if (reinvestment) {
// If we don't have enough ETH to do the reinvestment, withdraw.
if (address(this).balance < eth && hourglass.myDividends(true) > 0) {
hourglass.withdraw();
}
// If we _still_ don't have enough ETH to do the reinvestment, have the refHandler sends us some.
if (address(this).balance < eth) {
refHandler.sendETH(address(this), eth - address(this).balance);
}
}
hourglass.buy.value(eth)(invalidMasternode ? NULL_ADDRESS : (usedHourglassMasternode ? referrer : address(refHandler)));
}
// Use the delta from before and after the buy order to get the amount of P3D created.
createdTokens = hourglass.totalSupply() - createdTokens;
totalSupply += createdTokens;
// This is here for when someone transfers P3D to the contract directly. We have no way of knowing who it's from, so we'll just give it to the next person who happens to buy.
uint256 bonusTokens = hourglass.myTokens() + tmp - totalSupply;
// Here I now re-use that uint256 to create the bit flags.
tmp = 0;
if (invalidMasternode) { tmp |= 1; }
if (usedHourglassMasternode) { tmp |= 2; }
if (reinvestment) { tmp |= 4; }
emit onTokenPurchase(creator, eth, createdTokens, bonusTokens, referrer, uint8(tmp));
createdTokens += bonusTokens;
// We can finally give the P3X to the buyer!
balances[creator] += createdTokens;
totalSupply += bonusTokens;
//Updates services like etherscan which track token hodlings.
emit Transfer(address(this), creator, createdTokens, "");
emit Transfer(address(this), creator, createdTokens);
// Unfortunatly, SafeMath cannot be used here, otherwise the stack gets too deep
payouts[creator] += int256(profitPerShare * createdTokens); // You don't deserve the dividends before you owned the tokens.
if (reinvestment) {
// No dividend distribution underflows allowed.
// Ethereum has been given away after a "reinvestment" purchase, so we have to keep track of that.
lastTotalBalance = lastTotalBalance.sub(eth);
}
distributeDividends((usedHourglassMasternode || invalidMasternode) ? 0 : referralBonus, referrer);
if (referrer != NULL_ADDRESS) {
// Save the referrer for next time!
savedReferral[creator] = referrer;
}
return createdTokens;
}
// This is marked as an internal function because selling could have been the result of transfering P3X to the contract via a transferFrom transaction.
function destroyTokens(address weakHand, uint256 bags) internal returns(uint256) {
require(updateUsableBalanceOf(weakHand) >= bags, "Insufficient balance");
// Give the weak hand the last of their deserved payout.
// Also updates lastTotalBalance
distributeDividends(0, NULL_ADDRESS);
uint256 tokenBalance = hourglass.myTokens();
// We can't rely on ETH balance delta because we get cut of the sell fee ourselves.
uint256 ethReceived = hourglass.calculateEthereumReceived(bags);
lastTotalBalance += ethReceived;
if (tokenBalance >= bags) {
hourglass.sell(bags);
} else {
// If we don't have enough P3D to sell ourselves, get the slave to sell some, too.
if (tokenBalance > 0) {
hourglass.sell(tokenBalance);
}
refHandler.sellTokens(bags - tokenBalance);
}
// Put the ETH in outstanding dividends, and allow the weak hand access to the divs they've accumilated before they sold.
int256 updatedPayouts = int256(profitPerShare * bags + (ethReceived * ROUNDING_MAGNITUDE));
payouts[weakHand] = payouts[weakHand].sub(updatedPayouts);
// We already checked the balance of the weakHanded person, so SafeMathing here is redundant.
balances[weakHand] -= bags;
totalSupply -= bags;
emit onTokenSell(weakHand, bags, ethReceived);
// Tell etherscan of this tragity.
emit Transfer(weakHand, address(this), bags, "");
emit Transfer(weakHand, address(this), bags);
return ethReceived;
}
// sends ETH to the specified account, using all the ETH P3X has access to.
function sendETH(address payable to, uint256 amount) internal {
uint256 childTotalBalance = refHandler.totalBalance();
uint256 thisBalance = address(this).balance;
uint256 thisTotalBalance = thisBalance + hourglass.myDividends(true);
if (childTotalBalance >= amount) {
// the refHanlder has enough of its own ETH to send, so it should do that.
refHandler.sendETH(to, amount);
} else if (thisTotalBalance >= amount) {
// We have enough ETH of our own to send.
if (thisBalance < amount) {
hourglass.withdraw();
}
to.transfer(amount);
} else {
// Neither we nor the refHandler has enough ETH to send individually, so both contracts have to send ETH.
refHandler.sendETH(to, childTotalBalance);
if (hourglass.myDividends(true) > 0) {
hourglass.withdraw();
}
to.transfer(amount - childTotalBalance);
}
// keep the dividend tracker in check.
lastTotalBalance = lastTotalBalance.sub(amount);
}
// Take the ETH we've got and distribute it among our token holders.
function distributeDividends(uint256 bonus, address bonuser) internal{
// Prevents "HELP I WAS THE LAST PERSON WHO SOLD AND I CAN'T WITHDRAW MY ETH WHAT DO????" (dividing by 0 results in a crash)
if (totalSupply > 0) {
uint256 tb = totalBalance();
uint256 delta = tb - lastTotalBalance;
if (delta > 0) {
// We have more ETH than before, so we'll just distribute those dividends among our token holders.
if (bonus != 0) {
bonuses[bonuser] += bonus;
}
profitPerShare = profitPerShare.add(((delta - bonus) * ROUNDING_MAGNITUDE) / totalSupply);
lastTotalBalance += delta;
}
}
}
// Clear out someone's dividends.
function clearDividends(address accountHolder) internal returns(uint256, uint256) {
uint256 payout = dividendsOf(accountHolder, false);
uint256 bonusPayout = bonuses[accountHolder];
payouts[accountHolder] += int256(payout * ROUNDING_MAGNITUDE);
bonuses[accountHolder] = 0;
// External apps can now get reliable masternode statistics
return (payout, bonusPayout);
}
// Withdraw 100% of someone's dividends
function withdrawDividends(address payable accountHolder) internal {
distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened.
uint256 payout;
uint256 bonusPayout;
(payout, bonusPayout) = clearDividends(accountHolder);
emit onWithdraw(accountHolder, payout, bonusPayout, false);
sendETH(accountHolder, payout + bonusPayout);
}
// The internal transfer function.
function actualTransfer (address payable from, address payable to, uint value, bytes memory data, string memory func, bool careAboutHumanity) internal{
require(updateUsableBalanceOf(from) >= value, "Insufficient balance");
require(to != address(refHandler), "My slave doesn't get paid"); // I don't know why anyone would do this, but w/e
require(to != address(hourglass), "P3D has no need for these"); // Prevent l33x h4x0rs from having P3X call arbitrary P3D functions.
if (to == address(this)) {
// Treat transfers to this contract as a sell and withdraw order.
if (value == 0) {
// Transfers of 0 still have to be emitted... for some reason.
emit Transfer(from, to, value, data);
emit Transfer(from, to, value);
} else {
destroyTokens(from, value);
}
withdrawDividends(from);
} else {
distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened.
// I was going to add a value == 0 check here, but if you're sending 0 tokens to someone, you deserve to pay for wasted gas.
// Throwing an exception undos all changes. Otherwise changing the balance now would be a shitshow
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
// Sender can have their dividends from when they owned the tokens
payouts[from] -= int256(profitPerShare * value);
// Receiver is not allowed to have dividends from before they owned the tokens.
payouts[to] += int256(profitPerShare * value);
if (careAboutHumanity && isContract(to)) {
if (bytes(func).length == 0) {
ERC223Handler receiver = ERC223Handler(to);
receiver.tokenFallback(from, value, data);
} else {
bool success;
bytes memory returnData;
(success, returnData) = to.call.value(0)(abi.encodeWithSignature(func, from, value, data));
assert(success);
}
}
emit Transfer(from, to, value, data);
emit Transfer(from, to, value);
}
}
// The playerbook contract accepts a bytes32. We'll be converting for convenience sense.
function bytesToBytes32(bytes memory data) internal pure returns(bytes32){
uint256 result = 0;
uint256 len = data.length;
uint256 singleByte;
for (uint256 i = 0; i<len; i+=1){
singleByte = uint256(uint8(data[i])) << ( (31 - i) * 8);
require(singleByte != 0, "bytes cannot contain a null byte");
result |= singleByte;
}
return bytes32(result);
}
// haha casting types.
function stringToBytes32(string memory data) internal pure returns(bytes32){
return bytesToBytes32(bytes(data));
}
// If bytecode exists at _addr then the _addr is a contract.
function isContract(address _addr) internal view returns(bool) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
// Reject possible accidental sendin of higher-tech shitcoins. (with a fancy message)
function tokenFallback(address from, uint value, bytes memory data) public pure{
revert("I don't want your shitcoins!");
}
// Allow anyone else to take forcefully sent low-tech shitcoins. (I sure as hell don't want them)
function takeShitcoin(address shitCoin) public{
// Don't allow people to siphon funds from us
require(shitCoin != address(hourglass), "P3D isn't a shitcoin");
ERC20interface s = ERC20interface(shitCoin);
s.transfer(msg.sender, s.balanceOf(address(this)));
}
}
/**
* @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 || b == 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;
}
/**
* @dev Subtracts two numbers, throws on underflow
*/
function sub(int256 a, int256 b) internal pure returns(int256 c) {
c = a - b;
assert(c <= a);
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(int256 a, int256 b) internal pure returns(int256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | Withdraw outstanding divs to internal balance | function withdrawDivs() public onlyParent {
hourglass.withdraw();
}
| 1,778,953 |
./full_match/1/0xD58868004D5aac1FD0Da76D3b553aB2ed5354385/sources/contracts/PaymentSplitterEP.sol | NOTE: take care of how much accounts you use in case gas consumption goes to infinity/ | function releaseMany(address payable[] memory accounts) public virtual {
for (uint i = 0; i < accounts.length; i++) {
release(accounts[i]);
}
}
| 9,708,788 |
pragma solidity 0.6.12;
import "./ITreasury.sol";
contract Treasury is ITreasury {
/** @dev Constants */
// Minimum value required to be transfered when creating any proposal
uint256 public proposalMinDeposit = 100 ether;
// Percentage (out of 100) of the funds that correspond to gitcoin
uint256 public gitcoinRewardPerc = 10;
// Time between proposal creation and it's completion
uint256 public proposalDebatingPeriod = 30 days;
// Time between last lock funds and the availability for usage of any funds locked by the participant
uint256 public lockedWaitingTime = 1 days;
// Percentage (out of 100) of the stake on voting that have to be in favour of a proposal for it to be accepted
uint256 public proposalMajorityPerc = 60;
// Time before the proposalDebatingPeriod ending, for when the proposal has to be pre-approved
uint256 public proposalPreSupportPeriod = 2 days;
// Time since shutdown is scheduled till it can be executed
uint256 public shutdownGracePeriod = 7 days;
// FIXME (issue #6):
// min quorum was set to 30% of the total supply at the moment of development of this
// contract but the value should be dinamically calculated (at least based on an estimation
// of it)
// Amount of ETC required to have participated on the voting for this proposal to be applicable
function proposalMinQuourum() virtual public pure returns(uint256) { return 35000000 ether; }
enum ProposalType { AddClient, RemoveClient, RemoveGitcoin, UpdateMemberAddress, Shutdown }
struct Proposal {
// EFFECT INFO
ProposalType proposalType;
// Meaning depends on proposalType:
// - AddClient: client to be added if proposal successful
// - RemoveClient: client to be removed if proposal successful
// - UpdateMemberAddress: old client address if proposal successful
// - RemoveGitcoin or Shutdown: this value is not used
address votedAddress1;
// Meaning depends on proposalType:
// - UpdateMemberAddress: new client address if proposal successful
// - AddClient, RemoveClient, RemoveGitcoin or Shutdown: this value is not used
address votedAddress2;
// CREATOR INFO
address creator;
uint256 deposit;
// TIME INFO
uint256 proposedAtTime;
// VOTING INFO
// stake in favour of proposal
uint256 votesForYes;
// stake against proposal
uint256 votesForNo;
// mapping to get the stake voted in favour by a participant
mapping (address => uint256) votedYes;
// mapping to get the stake voted against by a participant
mapping (address => uint256) votedNo;
// STATE INFO
// True if the proposal has not been yet executed nor close
bool active;
// true if more tokens are in favour of the proposal than opposed to it at
// least `proposalPreSupportPeriod` before the voting deadline
bool preSupport;
}
struct LockedFunds {
// amount locked by user
uint256 amount;
// last time the user locked funds
uint256 lastLockedTime;
}
struct Member {
// amount locked by user
address recipient;
// Name that identifies this client
string name;
}
/** @dev Members */
bool gitcoinEnabled = true;
Member gitcoinMember;
Member[] clients;
/** @dev Funds distribution */
// Map of member addresses (including already removed ones) to pending amount to withdraw
mapping (address => uint256) pendingWithdraws;
/// @dev Total members available funds
uint256 totalMembersFunds = 0;
/** @dev Proposal tracking */
uint256 sumOfProposalDeposits = 0;
// FIXME: should we prune executed/closed proposals?
Proposal[] proposals;
/** @dev Stake locking */
// Map of participant addresses to:
// - amount locked
// - last time funds were unlocked, affects when they can be used
mapping (address => LockedFunds) lockedFunds;
uint256 totalLockedFunds = 0;
// Map of address to the proposal id blocking their funds
// During a vote the funds from a participant are blocked, that is, their funds can't be widthdrawl
mapping (address => uint256) blocked;
uint256 shutdownScheduledAt = 0;
// FIXME (issue #4): should we pass the names as well?
constructor (address _gitcoinAddress, address[] memory _clients) public {
gitcoinMember = Member(_gitcoinAddress, "Gitcoin");
for (uint i = 0; i < _clients.length; i++) {
clients.push(Member(_clients[i], ""));
}
}
// ---------------------
// WITHDRAWAL
// ---------------------
receive() external override payable { }
/// @dev assumes the client member list will be short enough to be iterable
function distributeFunds() public override {
// contract balance is compose by locks, deposits and rewards
uint256 fundsToDistribute =
address(this).balance - totalLockedFunds - sumOfProposalDeposits - totalMembersFunds;
uint256 fundsForGitcoin = 0;
// Distribute gitcoin's funds
if(gitcoinEnabled) {
fundsForGitcoin = fundsToDistribute * gitcoinRewardPerc / 100;
pendingWithdraws[gitcoinMember.recipient] += fundsForGitcoin;
totalMembersFunds += fundsForGitcoin;
}
// Distribute client's funds
// There might be some dust left that will be used for the next distribution, as it
// will be at most clients.length (assumed to not be too large)
if(clients.length > 0) {
uint256 fundsForEachClient = (fundsToDistribute - fundsForGitcoin) / clients.length;
for (uint clientIndex = 0; clientIndex < clients.length; clientIndex++) {
pendingWithdraws[clients[clientIndex].recipient] += fundsForEachClient;
totalMembersFunds += fundsForEachClient;
}
} else {
// FIXME (issue #5): save the funds for future clients and update totalMembersFunds
}
}
/// @dev Reverts if transfer fails
function withdrawFunds() public override returns(bool) {
uint256 pendingWithdraw = pendingWithdraws[msg.sender];
if(pendingWithdraw == 0) {
return false;
} else {
delete pendingWithdraws[msg.sender];
totalMembersFunds -= pendingWithdraw;
bool transferSuccessful = transferTo(msg.sender, pendingWithdraw);
require(transferSuccessful, "Transfering pending withdraw failed");
return transferSuccessful;
}
}
// ---------------------
// LOCKING/UNLOCKING
// ---------------------
/// @dev If the user had locked any funds previously, the will all remain unusable till pas
function lockFunds() public override payable noShutdownScheduled returns(bool) {
uint256 previousLockedAmount = lockedFunds[msg.sender].amount;
lockedFunds[msg.sender] = LockedFunds (
previousLockedAmount + msg.value,
// all funds from users will be unusable until lockingWaitingTime has passed
now
);
totalLockedFunds += msg.value;
return true;
}
/// @dev transfers the amount to the sender, if available
/// reverts if not enought funds
/// reverts if funds are blocked in a proposal
function unlockFunds(uint256 amount) public override notBlocked {
LockedFunds memory senderlockedFunds = lockedFunds[msg.sender];
require(senderlockedFunds.amount >= amount, 'Not enough funds');
// Safe substraction as it was checked before
uint256 newLockedAmount = senderlockedFunds.amount - amount;
if (newLockedAmount == 0) {
delete lockedFunds[msg.sender];
} else {
lockedFunds[msg.sender] = LockedFunds(
newLockedAmount,
senderlockedFunds.lastLockedTime
);
}
totalLockedFunds -= amount;
// Transfer the locked amount back to the user
bool transferSuccessful = transferTo(msg.sender, amount);
require(transferSuccessful, "Transfering locked funds back to participant failed");
}
// ---------------------
// PROPOSAL CREATION
// ---------------------
function proposeAddClient(address clientToAdd) payable public override noShutdownScheduled {
uint256 proposalID = createProposalCommon(ProposalType.AddClient);
// Effect info
Proposal storage proposal = proposals[proposalID];
proposal.votedAddress1 = clientToAdd;
emit AddClientProposal(proposalID, msg.sender, clientToAdd);
}
function proposeRemoveClient(address clientToRemove) payable public override noShutdownScheduled {
uint256 proposalID = createProposalCommon(ProposalType.RemoveClient);
// Effect info
Proposal storage proposal = proposals[proposalID];
proposal.votedAddress1 = clientToRemove;
emit RemoveClientProposal(proposalID, msg.sender, clientToRemove);
}
function proposeRemoveGitcoin() payable public override noShutdownScheduled {
uint256 proposalID = createProposalCommon(ProposalType.RemoveGitcoin);
emit RemoveGitcoinProposal(proposalID, msg.sender);
}
function proposeUpdateMemberAddress(address memberToUpdate, address newMemberAddress) payable public override noShutdownScheduled {
uint256 proposalID = createProposalCommon(ProposalType.UpdateMemberAddress);
// Effect info
Proposal storage proposal = proposals[proposalID];
proposal.votedAddress1 = memberToUpdate;
proposal.votedAddress2 = newMemberAddress;
emit UpdateMemberAddressProposal(proposalID, msg.sender, memberToUpdate, newMemberAddress);
}
function proposeShutdown() payable public override noShutdownScheduled {
uint256 proposalID = createProposalCommon(ProposalType.Shutdown);
emit ShutdownProposal(proposalID, msg.sender);
}
// ---------------------
// PROPOSAL VOTING
// ---------------------
function vote(uint256 _proposalID, bool _supportsProposal) public override noShutdownScheduled {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
require(now < proposal.proposedAtTime + proposalDebatingPeriod, "Debating period ended");
LockedFunds storage voterLockedFunds = lockedFunds[msg.sender];
require(voterLockedFunds.lastLockedTime + lockedWaitingTime <= now, "No unlocked funds available for usage");
unRegisterVotesFor(proposal, msg.sender);
// Vote for proposal changes
if (_supportsProposal) {
proposal.votesForYes += voterLockedFunds.amount;
proposal.votedYes[msg.sender] = voterLockedFunds.amount;
} else {
proposal.votesForNo += voterLockedFunds.amount;
proposal.votedNo[msg.sender] = voterLockedFunds.amount;
}
// Will block voter funds in this proposal if corresponds
evalBlockingProposal(_proposalID, proposal.proposedAtTime);
}
function unvote(uint _proposalID) public override noShutdownScheduled {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
require(now < proposal.proposedAtTime + proposalDebatingPeriod, "Debating period ended");
unRegisterVotesFor(proposal, msg.sender);
}
// ---------------------
// PROPOSAL EXECUTION
// ---------------------
function preApprove(uint _proposalID) public override noShutdownScheduled {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
uint256 totalStakeVoted = proposal.votesForYes + proposal.votesForNo;
require(!proposal.preSupport, "Already pre-approved");
require(now <= proposal.proposedAtTime + proposalDebatingPeriod - proposalPreSupportPeriod, "Pre-approve deadline already reached");
require(totalStakeVoted >= proposalMinQuourum(), "Not enough quorum for pre-approval");
require(totalStakeVoted * proposalMajorityPerc / 100 <= proposal.votesForYes, "Not enough votes for yes");
proposal.preSupport = true;
}
function execProposal(uint256 _proposalID, uint256 clientIndex) public override noShutdownScheduled {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
endProposal(_proposalID);
(bool canBeExecuted, string memory errorMsg) = canBeExecuted(_proposalID);
require(canBeExecuted, errorMsg);
// Before introducing any change to the state, make sure all funds belongs to current memebers
distributeFunds();
if (proposal.proposalType == ProposalType.AddClient) {
addClient(proposal.votedAddress1);
} else if (proposal.proposalType == ProposalType.RemoveClient) {
removeClient(proposal.votedAddress1, clientIndex);
} else if (proposal.proposalType == ProposalType.RemoveGitcoin) {
removeGitcoin();
} else if (proposal.proposalType == ProposalType.UpdateMemberAddress) {
updateMemberAddress(proposal.votedAddress1, proposal.votedAddress2, clientIndex);
} else if (proposal.proposalType == ProposalType.Shutdown) {
scheduleShutdown();
}
}
function closeProposal(uint256 _proposalID) public override noShutdownScheduled {
endProposal(_proposalID);
(bool canBeExecuted, ) = canBeExecuted(_proposalID);
require(!canBeExecuted, "Proposal can be executed");
emit ClosedProposal(_proposalID);
}
function recoverProposalDeposit(uint _proposalID) public override {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
bool canRecoverDeposit = !proposal.active || withShutdownInProgress();
require(canRecoverDeposit, "Proposal should had finished or shutdown scheduled");
uint256 depositToReturn = proposal.deposit;
require(depositToReturn != 0, "Proposal deposit already recovered");
sumOfProposalDeposits -= depositToReturn;
// empty the proposal deposit
proposal.deposit = 0;
bool returnDepositSuccessful = transferTo(proposal.creator, depositToReturn);
require(returnDepositSuccessful, "Returning the deposit was not successful");
}
// ---------------------
// SHUTDOWN
// ---------------------
function shutdown() public override {
require(withShutdownInProgress(), "No shutdown in progress");
require(shutdownScheduledAt + shutdownGracePeriod < now, "Shutdown grace period not yet over");
// All funds from the contract are burned
selfdestruct(address(0));
}
// ---------------------
// QUERYING
// ---------------------
function getAvailableWithdrawBalance(address memberAddress) public override view returns(uint256) {
return pendingWithdraws[memberAddress];
}
function getLockedAmount(address participant) public override view returns(uint256) {
return lockedFunds[participant].amount;
}
function canUnlockFunds() public override view returns(bool) {
if (withShutdownInProgress()) {
return true;
}
uint256 blockingProposalID = blocked[msg.sender];
if(proposals.length > blockingProposalID) {
uint256 proposalDebateEndTime = proposals[blockingProposalID].proposedAtTime + proposalDebatingPeriod;
return (now > proposalDebateEndTime);
}
return true;
}
function getClientMembersSize() public override view returns(uint256) {
return clients.length;
}
function getClientMemberAt(uint256 index) public override view returns(address recipient, string memory name) {
Member storage client = clients[index];
(recipient, name) = (client.recipient, client.name);
}
function getGitcoinAddress() public override view returns(address) {
require(gitcoinEnabled, "Gitcoin was disabled");
return gitcoinMember.recipient;
}
function getProposalState(uint256 _proposalID) public override view returns(bool active, bool preSupport, uint256 proposedAtTime, uint256 endsAtTime, uint256 approvalVotes, uint256 declineVotes) {
Proposal storage proposal = proposals[_proposalID];
active = proposal.active;
preSupport = proposal.preSupport;
proposedAtTime = proposal.proposedAtTime;
endsAtTime = proposal.proposedAtTime + proposalDebatingPeriod;
approvalVotes = proposal.votesForYes;
declineVotes = proposal.votesForNo;
}
function withShutdownInProgress() public override view returns(bool) {
return shutdownScheduledAt != 0;
}
// ---------------------
// INTERNAL
// ---------------------
function transferTo(address to, uint256 amount) internal returns(bool) {
(bool transferSuccessful, ) = to.call.value(amount)("");
return transferSuccessful;
}
function unRegisterVotesFor(Proposal storage proposal, address voter) internal {
proposal.votesForYes -= proposal.votedYes[voter];
delete proposal.votedYes[voter];
proposal.votesForNo -= proposal.votedNo[voter];
delete proposal.votedNo[voter];
}
/// @dev Shared procedure to create any proposal of _proposalType.
/// The proposal is included in the proposals collection
/// @param _proposalType Proposal type to be create
/// @return proposalID of the created Proposal
function createProposalCommon(ProposalType _proposalType) internal withMinimumDeposit returns(uint256 proposalID) {
Proposal memory proposal;
proposalID = proposals.length;
// Proposal Type
proposal.proposalType = _proposalType;
// Creator info
proposal.creator = msg.sender;
proposal.deposit = msg.value;
// deposit are counted as yes votes
proposal.votesForYes = msg.value;
// Time info
proposal.proposedAtTime = now;
// The proposal starts as active and can receive votes
proposal.active = true;
proposals.push(proposal);
sumOfProposalDeposits += proposal.deposit;
}
function endProposal(uint256 _proposalID) internal {
Proposal storage proposal = proposals[_proposalID]; // invalid opcode in case of inexistant proposal
require(proposal.proposedAtTime + proposalDebatingPeriod <= now, "Debating period in progress");
require(proposal.active, "Ending a non active proposal");
// The proposal is now ended
proposal.active = false;
}
function addClient(address clientToAdd) internal {
// FIXME (issue #4): add name to the proposal or allow name owner editing
clients.push(Member(clientToAdd, ""));
emit ClientAdded(clientToAdd);
}
function removeClient(address clientToRemove, uint256 clientIndex) internal {
Member storage clientMember = clients[clientIndex];
require(clientMember.recipient == clientToRemove, 'Member not in index');
// Remove the address
if (clients.length > 0) {
clients[clientIndex] = clients[clients.length - 1];
clients.pop();
}
emit ClientRemoved(clientToRemove);
}
function removeGitcoin() internal {
gitcoinEnabled = false;
emit GitcoinRemoved();
}
function updateMemberAddress(address oldAddress, address newAddress, uint256 clientIndex) internal {
// Update tracked members addresses
if (oldAddress == gitcoinMember.recipient) {
gitcoinMember.recipient = newAddress;
} else {
Member storage clientMember = clients[clientIndex];
require(clientMember.recipient == oldAddress, 'Member not in index');
clients[clientIndex].recipient = newAddress;
}
// Update the pending withdraws
pendingWithdraws[newAddress] = pendingWithdraws[oldAddress];
delete pendingWithdraws[oldAddress];
emit MemberAddressUpdated(oldAddress, newAddress);
}
function scheduleShutdown() internal {
// Set the treasury on schedule shutdown state
shutdownScheduledAt = now;
emit ShutdownScheduled();
}
/// @dev Evaluates it the new Proposal should block user funds, if so, updates blocked
function evalBlockingProposal(uint256 proposalID, uint256 proposedAtTime) internal {
uint256 currentBlockingPorposalID = blocked[msg.sender];
Proposal storage currentBlockingPorposal = proposals[currentBlockingPorposalID];
// As debating periods are equal, we can compare by proposal creation time
if(proposedAtTime > currentBlockingPorposal.proposedAtTime)
blocked[msg.sender] = proposalID;
}
function canBeExecuted(uint256 _proposalID) internal view returns(bool, string memory) {
Proposal storage proposal = proposals[_proposalID];
uint256 totalStakeVoted = proposal.votesForYes + proposal.votesForNo;
bool hasQuorum = totalStakeVoted >= proposalMinQuourum();
bool hasMajorityInFavour = totalStakeVoted * proposalMajorityPerc / 100 <= proposal.votesForYes;
bool hasPreSupport = proposal.preSupport;
if(!hasQuorum)
return (false, "Not enough quorum for execution");
else if (!hasMajorityInFavour)
return (false, "Not enough votes for yes");
else if (!hasPreSupport)
return (false, "Proposal should be pre-approved");
else
return (true, "");
}
modifier withMinimumDeposit() {
require(msg.value >= proposalMinDeposit, "Deposit is lower than the minimum");
_;
}
/// @dev requires that the sender has no blocked funds
modifier notBlocked() {
require(canUnlockFunds(), "Funds are blocked");
_;
}
modifier noShutdownScheduled() {
require(!withShutdownInProgress(), "Shutdown in progress");
_;
}
}
| All funds from the contract are burned | function shutdown() public override {
require(withShutdownInProgress(), "No shutdown in progress");
require(shutdownScheduledAt + shutdownGracePeriod < now, "Shutdown grace period not yet over");
selfdestruct(address(0));
}
| 12,997,017 |
./partial_match/1/0x8a3515f5D127342fcBba56E13514D4A2391327e6/sources/contracts/interfaces/IPoolPositionMover.sol | IPool Defines the basic interface for an ParaSpace Pool./ Migration step0. User needs to breakup P2P orders on their own1. Repay Debt 1. if it's cAPE then deposit borrowed APE into old cAPE pool then repay 2. if it's not then just repay with borrowed tokens2. burn old NToken 1. move old NToken to new Pool, if it's staking BAYC/MAYC/BAKC it'll be automatically unstaked 2. withdrawERC721 and specify new NToken as recipient 3. mint new NToken3. burn old PToken 1. move old PToken to new Pool 2. withdraw and specify new PToken as recipient 3. mint new NToken4. Mint new debt | interface IPoolPositionMover {
function movePositionFromBendDAO(uint256[] calldata loanIds) external;
function movePositionFromParaSpace(
DataTypes.ParaSpacePositionMoveInfo calldata moveInfo
) external;
function claimUnderlying(
address[] calldata assets,
uint256[][] calldata agreementIds
) external;
pragma solidity ^0.8.0;
import {DataTypes} from "../protocol/libraries/types/DataTypes.sol";
import {ApeCoinStaking} from "../dependencies/yoga-labs/ApeCoinStaking.sol";
}
| 4,311,964 |
// SPDX-License-Identifier: MIT
/* solhint-disable var-name-mixedcase */
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./interfaces/ISwap.sol";
/**
* @title AirSwap: Atomic Token Swap
* @notice https://www.airswap.io/
*/
contract Swap is ISwap, Ownable {
using SafeERC20 for IERC20;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 public constant ORDER_TYPEHASH =
keccak256(
abi.encodePacked(
"Order(",
"uint256 nonce,",
"uint256 expiry,",
"address signerWallet,",
"address signerToken,",
"uint256 signerAmount,",
"uint256 protocolFee,",
"address senderWallet,",
"address senderToken,",
"uint256 senderAmount",
")"
)
);
bytes32 public constant DOMAIN_NAME = keccak256("SWAP");
bytes32 public constant DOMAIN_VERSION = keccak256("3");
uint256 public immutable DOMAIN_CHAIN_ID;
bytes32 public immutable DOMAIN_SEPARATOR;
uint256 internal constant MAX_PERCENTAGE = 100;
uint256 internal constant MAX_SCALE = 77;
uint256 internal constant MAX_ERROR_COUNT = 6;
uint256 public constant FEE_DIVISOR = 10000;
/**
* @notice Double mapping of signers to nonce groups to nonce states
* @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key
* @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used
*/
mapping(address => mapping(uint256 => uint256)) internal _nonceGroups;
mapping(address => address) public override authorized;
uint256 public protocolFee;
uint256 public protocolFeeLight;
address public protocolFeeWallet;
uint256 public rebateScale;
uint256 public rebateMax;
address public staking;
constructor(
uint256 _protocolFee,
uint256 _protocolFeeLight,
address _protocolFeeWallet,
uint256 _rebateScale,
uint256 _rebateMax,
address _staking
) {
require(_protocolFee < FEE_DIVISOR, "INVALID_FEE");
require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE");
require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET");
require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH");
require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
require(_staking != address(0), "INVALID_STAKING");
uint256 currentChainId = getChainId();
DOMAIN_CHAIN_ID = currentChainId;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
DOMAIN_NAME,
DOMAIN_VERSION,
currentChainId,
this
)
);
protocolFee = _protocolFee;
protocolFeeLight = _protocolFeeLight;
protocolFeeWallet = _protocolFeeWallet;
rebateScale = _rebateScale;
rebateMax = _rebateMax;
staking = _staking;
}
/**
* @notice Atomic ERC20 Swap
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swap(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
// Ensure the order is valid
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount);
// Calculate and transfer protocol fee and any rebate
_transferProtocolFee(signerToken, signerWallet, signerAmount);
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Swap Atomic ERC20 Swap (Low Gas Usage)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function light(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
// Recover the signatory from the hash and signature
address signatory = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
protocolFeeLight,
msg.sender,
senderToken,
senderAmount
)
)
)
),
v,
r,
s
);
// Ensure the signatory is not null
require(signatory != address(0), "SIGNATURE_INVALID");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Transfer fee from signer to feeWallet
IERC20(signerToken).safeTransferFrom(
signerWallet,
protocolFeeWallet,
(signerAmount * protocolFeeLight) / FEE_DIVISOR
);
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFeeLight,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Sender Buys an NFT (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC721 token transferred from the signer
* @param signerID uint256 Token ID transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function buyNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerID,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerID,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID);
// Calculate and transfer protocol fee and rebate
_transferProtocolFee(senderToken, msg.sender, senderAmount);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerID,
protocolFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Sender Sells an NFT (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC721 token transferred from the sender
* @param senderID uint256 Token ID transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function sellNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderID,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderID,
v,
r,
s
);
// Transfer token from sender to signer
IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Calculate and transfer protocol fee and rebate
_transferProtocolFee(signerToken, signerWallet, signerAmount);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFee,
msg.sender,
senderToken,
senderID
);
}
/**
* @notice Signer and sender swap NFTs (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC721 token transferred from the signer
* @param signerID uint256 Token ID transferred from the signer
* @param senderToken address ERC721 token transferred from the sender
* @param senderID uint256 Token ID transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapNFTs(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerID,
address senderToken,
uint256 senderID,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerID,
senderToken,
senderID,
v,
r,
s
);
// Transfer token from sender to signer
IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID);
// Transfer token from signer to sender
IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerID,
0,
msg.sender,
senderToken,
senderID
);
}
/**
* @notice Set the fee
* @param _protocolFee uint256 Value of the fee in basis points
*/
function setProtocolFee(uint256 _protocolFee) external onlyOwner {
// Ensure the fee is less than divisor
require(_protocolFee < FEE_DIVISOR, "INVALID_FEE");
protocolFee = _protocolFee;
emit SetProtocolFee(_protocolFee);
}
/**
* @notice Set the light fee
* @param _protocolFeeLight uint256 Value of the fee in basis points
*/
function setProtocolFeeLight(uint256 _protocolFeeLight) external onlyOwner {
// Ensure the fee is less than divisor
require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE_LIGHT");
protocolFeeLight = _protocolFeeLight;
emit SetProtocolFeeLight(_protocolFeeLight);
}
/**
* @notice Set the fee wallet
* @param _protocolFeeWallet address Wallet to transfer fee to
*/
function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner {
// Ensure the new fee wallet is not null
require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET");
protocolFeeWallet = _protocolFeeWallet;
emit SetProtocolFeeWallet(_protocolFeeWallet);
}
/**
* @notice Set scale
* @dev Only owner
* @param _rebateScale uint256
*/
function setRebateScale(uint256 _rebateScale) external onlyOwner {
require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH");
rebateScale = _rebateScale;
emit SetRebateScale(_rebateScale);
}
/**
* @notice Set max
* @dev Only owner
* @param _rebateMax uint256
*/
function setRebateMax(uint256 _rebateMax) external onlyOwner {
require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
rebateMax = _rebateMax;
emit SetRebateMax(_rebateMax);
}
/**
* @notice Set the staking token
* @param newstaking address Token to check balances on
*/
function setStaking(address newstaking) external onlyOwner {
// Ensure the new staking token is not null
require(newstaking != address(0), "INVALID_FEE_WALLET");
staking = newstaking;
emit SetStaking(newstaking);
}
/**
* @notice Authorize a signer
* @param signer address Wallet of the signer to authorize
* @dev Emits an Authorize event
*/
function authorize(address signer) external override {
require(signer != address(0), "SIGNER_INVALID");
authorized[msg.sender] = signer;
emit Authorize(signer, msg.sender);
}
/**
* @notice Revoke the signer
* @dev Emits a Revoke event
*/
function revoke() external override {
address tmp = authorized[msg.sender];
delete authorized[msg.sender];
emit Revoke(tmp, msg.sender);
}
/**
* @notice Cancel one or more nonces
* @dev Cancelled nonces are marked as used
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
function cancel(uint256[] calldata nonces) external override {
for (uint256 i = 0; i < nonces.length; i++) {
uint256 nonce = nonces[i];
if (_markNonceAsUsed(msg.sender, nonce)) {
emit Cancel(nonce, msg.sender);
}
}
}
/**
* @notice Validates Swap Order for any potential errors
* @param senderWallet address Wallet that would send the order
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
* @return tuple of error count and bytes32[] memory array of error messages
*/
function check(
address senderWallet,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (uint256, bytes32[] memory) {
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
Order memory order;
uint256 errCount;
order.nonce = nonce;
order.expiry = expiry;
order.signerWallet = signerWallet;
order.signerToken = signerToken;
order.signerAmount = signerAmount;
order.senderToken = senderToken;
order.senderAmount = senderAmount;
order.v = v;
order.r = r;
order.s = s;
order.senderWallet = senderWallet;
bytes32 hashed = _getOrderHash(
order.nonce,
order.expiry,
order.signerWallet,
order.signerToken,
order.signerAmount,
order.senderWallet,
order.senderToken,
order.senderAmount
);
address signatory = _getSignatory(hashed, order.v, order.r, order.s);
if (signatory == address(0)) {
errors[errCount] = "SIGNATURE_INVALID";
errCount++;
}
if (order.expiry < block.timestamp) {
errors[errCount] = "EXPIRY_PASSED";
errCount++;
}
if (
order.signerWallet != signatory &&
authorized[order.signerWallet] != signatory
) {
errors[errCount] = "UNAUTHORIZED";
errCount++;
} else {
if (nonceUsed(signatory, order.nonce)) {
errors[errCount] = "NONCE_ALREADY_USED";
errCount++;
}
}
uint256 signerBalance = IERC20(order.signerToken).balanceOf(
order.signerWallet
);
uint256 signerAllowance = IERC20(order.signerToken).allowance(
order.signerWallet,
address(this)
);
uint256 feeAmount = (order.signerAmount * protocolFee) / FEE_DIVISOR;
if (signerAllowance < order.signerAmount + feeAmount) {
errors[errCount] = "SIGNER_ALLOWANCE_LOW";
errCount++;
}
if (signerBalance < order.signerAmount + feeAmount) {
errors[errCount] = "SIGNER_BALANCE_LOW";
errCount++;
}
return (errCount, errors);
}
/**
* @notice Calculate output amount for an input score
* @param stakingBalance uint256
* @param feeAmount uint256
*/
function calculateDiscount(uint256 stakingBalance, uint256 feeAmount)
public
view
returns (uint256)
{
uint256 divisor = (uint256(10)**rebateScale) + stakingBalance;
return (rebateMax * stakingBalance * feeAmount) / divisor / 100;
}
/**
* @notice Calculates and refers fee amount
* @param wallet address
* @param amount uint256
*/
function calculateProtocolFee(address wallet, uint256 amount)
public
view
override
returns (uint256)
{
// Transfer fee from signer to feeWallet
uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR;
if (feeAmount > 0) {
uint256 discountAmount = calculateDiscount(
IERC20(staking).balanceOf(wallet),
feeAmount
);
return feeAmount - discountAmount;
}
return feeAmount;
}
/**
* @notice Returns true if the nonce has been used
* @param signer address Address of the signer
* @param nonce uint256 Nonce being checked
*/
function nonceUsed(address signer, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;
}
/**
* @notice Returns the current chainId using the chainid opcode
* @return id uint256 The chain id
*/
function getChainId() public view returns (uint256 id) {
// no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Marks a nonce as used for the given signer
* @param signer address Address of the signer for which to mark the nonce as used
* @param nonce uint256 Nonce to be marked as used
* @return bool True if the nonce was not marked as used already
*/
function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
/**
* @notice Checks Order Expiry, Nonce, Signature
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function _checkValidOrder(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 hashed = _getOrderHash(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
msg.sender,
senderToken,
senderAmount
);
// Recover the signatory from the hash and signature
address signatory = _getSignatory(hashed, v, r, s);
// Ensure the signatory is not null
require(signatory != address(0), "SIGNATURE_INVALID");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
}
/**
* @notice Hash order parameters
* @param nonce uint256
* @param expiry uint256
* @param signerWallet address
* @param signerToken address
* @param signerAmount uint256
* @param senderToken address
* @param senderAmount uint256
* @return bytes32
*/
function _getOrderHash(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderWallet,
address senderToken,
uint256 senderAmount
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
protocolFee,
senderWallet,
senderToken,
senderAmount
)
);
}
/**
* @notice Recover the signatory from a signature
* @param hash bytes32
* @param v uint8
* @param r bytes32
* @param s bytes32
*/
function _getSignatory(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (address) {
return
ecrecover(
keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)),
v,
r,
s
);
}
/**
* @notice Calculates and transfers protocol fee and rebate
* @param sourceToken address
* @param sourceWallet address
* @param amount uint256
*/
function _transferProtocolFee(
address sourceToken,
address sourceWallet,
uint256 amount
) internal {
// Transfer fee from signer to feeWallet
uint256 feeAmount = (amount * protocolFee) / FEE_DIVISOR;
if (feeAmount > 0) {
uint256 discountAmount = calculateDiscount(
IERC20(staking).balanceOf(msg.sender),
feeAmount
);
if (discountAmount > 0) {
// Transfer fee from signer to sender
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
msg.sender,
discountAmount
);
// Transfer fee from signer to feeWallet
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
protocolFeeWallet,
feeAmount - discountAmount
);
} else {
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
protocolFeeWallet,
feeAmount
);
}
}
}
}
// 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/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 (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
pragma solidity ^0.8.0;
interface ISwap {
struct Order {
uint256 nonce;
uint256 expiry;
address signerWallet;
address signerToken;
uint256 signerAmount;
address senderWallet;
address senderToken;
uint256 senderAmount;
uint8 v;
bytes32 r;
bytes32 s;
}
event Swap(
uint256 indexed nonce,
uint256 timestamp,
address indexed signerWallet,
address signerToken,
uint256 signerAmount,
uint256 protocolFee,
address indexed senderWallet,
address senderToken,
uint256 senderAmount
);
event Cancel(uint256 indexed nonce, address indexed signerWallet);
event Authorize(address indexed signer, address indexed signerWallet);
event Revoke(address indexed signer, address indexed signerWallet);
event SetProtocolFee(uint256 protocolFee);
event SetProtocolFeeLight(uint256 protocolFeeLight);
event SetProtocolFeeWallet(address indexed feeWallet);
event SetRebateScale(uint256 rebateScale);
event SetRebateMax(uint256 rebateMax);
event SetStaking(address indexed staking);
function swap(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function light(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function buyNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function sellNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function swapNFTs(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function authorize(address sender) external;
function revoke() external;
function cancel(uint256[] calldata nonces) external;
function nonceUsed(address, uint256) external view returns (bool);
function authorized(address) external view returns (address);
function calculateProtocolFee(address, uint256)
external
view
returns (uint256);
}
// 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/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);
}
// 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 (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/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);
} | Atomic ERC20 Swap nonce uint256 Unique and should be sequential expiry uint256 Expiry in seconds since 1 January 1970 signerWallet address Wallet of the signer signerToken address ERC20 token transferred from the signer signerAmount uint256 Amount transferred from the signer senderToken address ERC20 token transferred from the sender senderAmount uint256 Amount transferred from the sender v uint8 "v" value of the ECDSA signature r bytes32 "r" value of the ECDSA signature s bytes32 "s" value of the ECDSA signature/ Ensure the order is valid Transfer token from sender to signer Transfer token from signer to recipient Calculate and transfer protocol fee and any rebate Emit a Swap event | function swap(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount);
_transferProtocolFee(signerToken, signerWallet, signerAmount);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFee,
msg.sender,
senderToken,
senderAmount
);
}
| 10,367,295 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Letter.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
/// @title Letter Factory Contract
/// @author Bernardo A. Rodrigues
/// @notice Defines a Letter Factory, where new Clones of Letter Contract are deployed.
/// @dev Defines a Letter Factory, where new Clones of Letter Contract are deployed.
contract LetterFactory {
// Letter Contact to be cloned
address immutable _letterImplementation;
// Keep track of deployed clones
address[] private _letters;
/// @notice LetterFactory Constructor. Creates reference Letter Contract.
/// @dev LetterFactory Constructor. Creates reference Letter Contract.
constructor() {
_letterImplementation = address(new Letter());
}
/// @notice Creates a new Letter Contract Clone.
/// @dev Creates a new Letter Contract Clone.
/// @param _title Title of Letter to be created. Redirected to initLetter().
/// @param _firstPage Contents of the 1st Letter Page to be created. Redirected to initLetter().
/// @param _author Author Signature of the Letter (as in handwritten signature; NOT as in cryptographic signature). Redirected to initLetter().
/// @return address Address of deployed Letter Contract Clone.
function createLetter(string memory _title, string memory _firstPage, string memory _author)
external
returns (address) {
address letterClone = Clones.clone(_letterImplementation);
Letter(letterClone).initLetter(_title, _firstPage, _author, msg.sender);
_letters.push(letterClone);
return letterClone;
}
/// @notice Views how many Letter Contract Clones have been deployed.
/// @dev Views how many Letter Contract Clones have been deployed.
/// @return uint256 How many Letter Contract Clones have been deployed.
function viewLetterCount()
public
view
returns (uint256) {
return _letters.length;
}
/// @notice Views some Letter Contract Clone's Address.
/// @dev Views some Letter Contract Clone's Address.
/// @param _letterN Id of Letter Contract Clone.
/// @return address Address of Letter Contract Clone.
function viewLetterAddr(uint256 _letterN)
public
view
returns (address) {
return _letters[_letterN];
}
} | Creates a new Letter Contract Clone. Creates a new Letter Contract Clone. _title Title of Letter to be created. Redirected to initLetter(). _firstPage Contents of the 1st Letter Page to be created. Redirected to initLetter(). _author Author Signature of the Letter (as in handwritten signature; NOT as in cryptographic signature). Redirected to initLetter(). return address Address of deployed Letter Contract Clone. | function createLetter(string memory _title, string memory _firstPage, string memory _author)
external
returns (address) {
address letterClone = Clones.clone(_letterImplementation);
Letter(letterClone).initLetter(_title, _firstPage, _author, msg.sender);
_letters.push(letterClone);
return letterClone;
}
| 15,869,882 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
/**
* @title Owner
* @dev Set & change owner
*/
contract Owner {
address private owner;
// event for EVM logging
event OwnerSet(address indexed oldOwner, address indexed newOwner);
// modifier to check if caller is owner
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner");
_;
}
/**
* @dev Set contract deployer as owner
*/
constructor() {
owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
emit OwnerSet(address(0), owner);
}
/**
* @dev Change owner
* @param newOwner address of new owner
*/
function changeOwner(address newOwner) public isOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
/**
* @dev Return owner address
* @return address of owner
*/
function getOwner() public view returns (address) {
return owner;
}
}
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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, 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 defaut 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");
_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");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= 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 { }
}
/**
* @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;
}
}
/**
* @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;
}
}
/**
* @dev Contract for Staking ERC-20 Tokens and pay interest on real time
*/
contract StakeContract is Owner, ReentrancyGuard {
// safe uint256
using SafeMath for uint256;
// the token to be used for staking
ERC20 public token;
// Annual Percentage Yield
uint8 public APY;
// minimum stake time in seconds, if the user withdraws before this time a penalty will be charged
uint256 public minimumStakeTime;
// the penalty, a number between 0 and 100
uint8 public penalty;
// penalties are collected and stored by the contract
uint256 private collectedPenalty;
// the Stake
struct Stake {
// opening timestamp
uint256 startDate;
// amount staked
uint256 amount;
// interest accrued, this will be available only after closing stake
uint256 interest;
// penalty charged, if any
uint256 penalty;
// closing timestamp
uint256 finishedDate;
// is closed or not
bool closed;
}
// stakes that the owner have
mapping(address => Stake[]) private stakesOfOwner;
// all accounts that have or have had stakes, this for the owner to be able to query stakes
address[] private ownersAccounts;
// @param _apy: APY 0 to 100
// @param _mst: minimum stake time in seconds
// @param _penalty: the penalty percentage 0 to 100
// @_token: the ERC20 token to be used
constructor(uint8 _apy, uint256 _mst, uint8 _penalty, ERC20 _token) {
token = _token;
require(_apy<=100, "APY has to be lower or equal than 100");
require(_penalty<=100, "Penalty has to be lower or equal than 100");
APY = _apy;
minimumStakeTime = _mst;
penalty = _penalty;
}
// owner can change the basic parameters of the contract
// interest will be recalculated in real time for all accounts if changed
function modifyAnnualInterestRatePercentage(uint8 _newVal) external isOwner {
APY = _newVal;
}
function modifyMinimumStakeTime(uint256 _newVal) external isOwner {
minimumStakeTime = _newVal;
}
function modifyPenalty(uint8 _newVal) external isOwner {
penalty = _newVal;
}
// owner can query all stake accounts holders
function queryOwnersAccounts() external view isOwner returns (address[] memory) {
return ownersAccounts;
}
function calculateInterest(address _ownerAccount, uint256 i) private view returns (uint256) {
// APY per year = amount * APY / 100 / seconds of the year
uint256 interest_per_year = stakesOfOwner[_ownerAccount][i].amount.mul(APY).div(100);
// number of seconds since opening date
uint256 num_seconds = block.timestamp.sub(stakesOfOwner[_ownerAccount][i].startDate);
// calculate interest by a rule of three
// seconds of the year: 31536000 = 365*24*60*60
// interest_per_year - 31536000
// interest - num_seconds
// interest = num_seconds * interest_per_year / 31536000
return num_seconds.mul(interest_per_year).div(31536000);
}
// stake holders or owner can query the stakes
function queryStakesOfOwner(address _ownerAccount) external view returns (uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory, bool[] memory) {
// sender is querying their own account, or owner is querying stakes
require(msg.sender==_ownerAccount || msg.sender==getOwner(), "You dont have permission");
// create arrays to return results
uint256[] memory startDate_r = new uint256[](stakesOfOwner[_ownerAccount].length);
uint256[] memory amount_r = new uint256[](stakesOfOwner[_ownerAccount].length);
uint256[] memory interest_r = new uint256[](stakesOfOwner[_ownerAccount].length);
uint256[] memory penalty_r = new uint256[](stakesOfOwner[_ownerAccount].length);
uint256[] memory finishedDate_r = new uint256[](stakesOfOwner[_ownerAccount].length);
bool[] memory closed_r = new bool[](stakesOfOwner[_ownerAccount].length);
// loop the stakes and store them in the array of results
for(uint256 i=0; i<stakesOfOwner[_ownerAccount].length; i++){
startDate_r[i] = stakesOfOwner[_ownerAccount][i].startDate;
amount_r[i] = stakesOfOwner[_ownerAccount][i].amount;
// if the stake is closed return the interest, otherwise calculate it in real time
if(stakesOfOwner[_ownerAccount][i].closed == true){
interest_r[i] = stakesOfOwner[_ownerAccount][i].interest;
}else{
// calculate interest
interest_r[i] = calculateInterest(_ownerAccount, i);
}
penalty_r[i] = stakesOfOwner[_ownerAccount][i].penalty;
finishedDate_r[i] = stakesOfOwner[_ownerAccount][i].finishedDate;
closed_r[i] = stakesOfOwner[_ownerAccount][i].closed;
}
return (startDate_r, amount_r, interest_r, penalty_r, finishedDate_r, closed_r);
}
// anyone can create a stake
function createStake(uint256 amount) external {
// store the tokens of the user in the contract
// requires approve
token.transferFrom(msg.sender, address(this), amount);
// store the account of the staker in ownersAccounts if it doesnt exists
if(stakesOfOwner[msg.sender].length == 0){
ownersAccounts.push(msg.sender);
}
// create the stake
stakesOfOwner[msg.sender].push(Stake(block.timestamp, amount, 0, 0, 0, false));
}
// finalize the stake and pay interest or charge penalty accordingly
// arrayIndex: is the id of the stake to be finalized
function withdrawStake(uint256 arrayIndex) external nonReentrant {
// Stake should exists and opened
require(arrayIndex < stakesOfOwner[msg.sender].length, "Stake does not exist");
require(stakesOfOwner[msg.sender][arrayIndex].closed==false, "This stake is closed");
// charge penalty if below minimum stake time
if(block.timestamp.sub(stakesOfOwner[msg.sender][arrayIndex].startDate) < minimumStakeTime){
// calculate penalty = amount * penalty / 100
uint256 the_penalty = stakesOfOwner[msg.sender][arrayIndex].amount.mul(penalty).div(100);
// remaining amount= amount - penaty
uint256 amountToWithdraw = stakesOfOwner[msg.sender][arrayIndex].amount.sub(the_penalty);
// transfer remaining
token.transfer(msg.sender, amountToWithdraw);
// penalty funds are hold by the contract, but keep the account of how much is it here
collectedPenalty = collectedPenalty.add(the_penalty);
// store the results in the stakes array of the user
stakesOfOwner[msg.sender][arrayIndex].penalty = the_penalty;
stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp;
stakesOfOwner[msg.sender][arrayIndex].closed = true;
// pay interest if above or equal minimum stake time
}else{
// get the interest
uint256 interest = calculateInterest(msg.sender, arrayIndex);
// transfer the interes from owner account, it has to have enough funds approved
token.transferFrom(getOwner(), msg.sender, interest);
// transfer the amount from the contract itself
token.transfer(msg.sender, stakesOfOwner[msg.sender][arrayIndex].amount);
// record the transaction
stakesOfOwner[msg.sender][arrayIndex].interest = interest;
stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp;
stakesOfOwner[msg.sender][arrayIndex].closed = true;
}
}
// owner can query and collect the penalty stored in the contract
function queryCollectedPenalty() external view isOwner returns (uint256) {
return collectedPenalty;
}
function withdrawPenalty() external isOwner nonReentrant {
token.transfer(msg.sender, collectedPenalty);
collectedPenalty = 0;
}
} | owner can query and collect the penalty stored in the contract | function queryCollectedPenalty() external view isOwner returns (uint256) {
return collectedPenalty;
}
| 13,580,188 |
pragma solidity 0.4.13;
/**
* @title Wallet Getter Library
* @author Majoolr.io
*
* version 1.0.0
* Copyright (c) 2017 Majoolr, LLC
* The MIT License (MIT)
* https://github.com/Majoolr/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. Majoolr 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.
* Majoolr also strives to educate non-profits, schools, and other community
* members about the application of blockchain technology. For further
* information: majoolr.io, 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.
*/
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) constant returns (address[51]) {
address[51] memory o;
for(uint 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 uint Index of the owner
function getOwnerIndex(WalletMainLib.WalletData storage self, address _owner) constant returns (uint) {
return self.ownerIndex[_owner];
}
/// @dev Get max number of wallet owners
/// @param self Wallet in contract storage
/// @return uint Maximum number of owners
function getMaxOwners(WalletMainLib.WalletData storage self) constant returns (uint) {
return self.maxOwners;
}
/// @dev Get number of wallet owners
/// @param self Wallet in contract storage
/// @return uint Number of owners
function getOwnerCount(WalletMainLib.WalletData storage self) constant returns (uint) {
return self.owners.length - 1;
}
/// @dev Get sig requirements for administrative changes
/// @param self Wallet in contract storage
/// @return uint Number of sigs required
function getRequiredAdmin(WalletMainLib.WalletData storage self) constant returns (uint) {
return self.requiredAdmin;
}
/// @dev Get sig requirements for minor tx spends
/// @param self Wallet in contract storage
/// @return uint Number of sigs required
function getRequiredMinor(WalletMainLib.WalletData storage self) constant returns (uint) {
return self.requiredMinor;
}
/// @dev Get sig requirements for major tx spends
/// @param self Wallet in contract storage
/// @return uint Number of sigs required
function getRequiredMajor(WalletMainLib.WalletData storage self) constant returns (uint) {
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 uint[2] 0-index is day timestamp, 1-index is the day spend
function getCurrentSpend(WalletMainLib.WalletData storage self, address _token) constant returns (uint[2]) {
uint[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 uint Threshold amount
function getMajorThreshold(WalletMainLib.WalletData storage self, address _token) constant returns (uint) {
return self.majorThreshold[_token];
}
/// @dev Get last 10 transactions for the day, fixed at 10 until fork
/// @param self Wallet in contract storage
/// @param _date Timestamp of day requested
/// @return bytes32[10] Last 10 tx's starting with latest
function getTransactions(WalletMainLib.WalletData storage self, uint _date) constant returns (bytes32[10]) {
bytes32[10] memory t;
uint li = self.transactions[_date].length - 1;
for(uint i = li; i >= 0; i--){
t[li - i] = self.transactions[_date][i];
}
return t;
}
/// @dev Get the number of tx's with the same id
/// @param self Wallet in contract storage
/// @param _id ID of transactions requested
/// @return uint Number of tx's with same ID
function getTransactionLength(WalletMainLib.WalletData storage self, bytes32 _id) constant returns (uint) {
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 _number The transaction index number
/// @return uint256[50] Returns list of confirmations, fixed at 50 until fork
function getTransactionConfirms(WalletMainLib.WalletData storage self,
bytes32 _id,
uint _number)
constant returns (uint256[50])
{
uint256[50] memory tc;
for(uint i = 0; i<self.transactionInfo[_id][_number].confirmedOwners.length; i++){
tc[i] = self.transactionInfo[_id][_number].confirmedOwners[i];
}
return tc;
}
/// @dev Retrieve tx confirmation count
/// @param self Wallet in contract storage
/// @param _id ID of transaction requested
/// @param _number The transaction index number
/// @return uint Returns the current number of tx confirmations
function getTransactionConfirmCount(WalletMainLib.WalletData storage self,
bytes32 _id,
uint _number)
constant returns(uint)
{
return self.transactionInfo[_id][_number].confirmCount;
}
/// @dev Retrieve if transaction was successful
/// @param self Wallet in contract storage
/// @param _id ID of transaction requested
/// @param _number The transaction index number
/// @return bool Returns true if tx successfully executed, false otherwise
function getTransactionSuccess(WalletMainLib.WalletData storage self,
bytes32 _id,
uint _number)
constant returns (bool)
{
return self.transactionInfo[_id][_number].success;
}
}
pragma solidity 0.4.13;
/**
* @title Wallet Main Library
* @author Majoolr.io
*
* version 1.0.0
* Copyright (c) 2017 Majoolr, LLC
* The MIT License (MIT)
* https://github.com/Majoolr/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. Majoolr 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.
* Majoolr also strives to educate non-profits, schools, and other community
* members about the application of blockchain technology. For further
* information: majoolr.io, 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.
*/
library WalletMainLib {
using Array256Lib for uint256[];
using BasicMathLib for uint;
struct WalletData {
uint maxOwners; //Maximum wallet owners, should be 50
address[] owners; //Array of all owners
uint requiredAdmin; //Number of sigs required for administrative changes
uint requiredMajor; //Number of sigs required for major transactions
uint requiredMinor; //Number of sigs required for minor transactions
// The amount of a token spent per day, ether is at address mapping 0,
// all other tokens defined by address. uint[0] corresponds to the current
// day, uint[1] is the spend amount
mapping (address => uint[2]) currentSpend;
//The day spend threshold for transactions to be major, ether at 0, all others by address
mapping (address => uint) majorThreshold;
//Array of transactions per day, uint is the day timestamp, bytes32 is the transaction id
mapping (uint => bytes32[]) transactions;
//Tracks the index of each owner in the owners Array
mapping (address => uint) ownerIndex;
//Array of Transaction's by id, new tx's with exact inputs as previous tx will add to array
mapping (bytes32 => Transaction[]) transactionInfo;
}
struct Transaction {
uint day; //Timestamp of the day initialized
uint value; //Amount of ether being sent
address tokenAdress; //Address of token transferred
uint amount; //Amount of tokens transferred
bytes data; //Temp location for pending transactions, erased after final confirmation
uint256[] confirmedOwners; //Array of owners confirming transaction
uint confirmCount; //Tracks the number of confirms
uint confirmRequired; //Number of sigs required for this transaction
bool success; //True after final confirmation
}
/*Events*/
event LogRevokeNotice(bytes32 txid, address sender, uint confirmsNeeded);
event LogTransactionFailed(bytes32 txid, address sender);
event LogTransactionConfirmed(bytes32 txid, address sender, uint confirmsNeeded);
event LogTransactionComplete(bytes32 txid, address target, uint value, bytes data);
event LogContractCreated(address newContract, uint value);
event LogErrMsg(string msg);
/// @dev Constructor
/// @param self The wallet in contract storage
/// @param _owners Array of initial owners
/// @param _requiredAdmin Set number of sigs for administrative tasks
/// @param _requiredMajor Set number of sigs for major tx
/// @param _requiredMinor Set number of sigs for minor tx
/// @param _majorThreshold Set major tx threshold amount for ether
/// @return Will return true when complete
function init(WalletData storage self,
address[] _owners,
uint _requiredAdmin,
uint _requiredMajor,
uint _requiredMinor,
uint _majorThreshold) returns (bool)
{
require(self.owners.length == 0);
require(_owners.length >= _requiredAdmin && _requiredAdmin > 0);
require(_owners.length >= _requiredMajor && _requiredMajor > 0);
require(_owners.length >= _requiredMinor && _requiredMinor > 0);
self.owners.push(0); //Leave index-0 empty for easier owner checks
for (uint i=0; i<_owners.length; i++) {
require(_owners[i] != 0);
self.owners.push(_owners[i]);
self.ownerIndex[_owners[i]] = i+1;
}
self.requiredAdmin = _requiredAdmin;
self.requiredMajor = _requiredMajor;
self.requiredMinor = _requiredMinor;
self.maxOwners = 50; //Limits to 50 owners, should create wallet pools for more owners
self.majorThreshold[0] = _majorThreshold; //Sets ether threshold at address 0
return true;
}
/*Checks*/
/// @dev Verifies a confirming owner has not confirmed already
/// @param self Contract wallet in storage
/// @param _id ID of the tx being checked
/// @param _number Index number of this tx
/// @return Returns true if check passes, false otherwise
function checkNotConfirmed(WalletData storage self, bytes32 _id, uint _number)
constant returns (bool)
{
require(self.ownerIndex[msg.sender] > 0);
uint _txLen = self.transactionInfo[_id].length;
if(_txLen == 0 || _number >= _txLen){
LogErrMsg("Tx not initiated");
LogTransactionFailed(_id, msg.sender);
return false;
}
if(self.transactionInfo[_id][_number].success){
LogErrMsg("Transaction already complete");
LogTransactionFailed(_id, msg.sender);
return false;
}
//Function from Majoolr.io array utility library
bool found;
uint index;
(found, index) = self.transactionInfo[_id][_number].confirmedOwners.indexOf(uint(msg.sender), false);
if(found){
LogErrMsg("Owner already confirmed");
LogTransactionFailed(_id, msg.sender);
return false;
}
return true;
}
/*Utility Functions*/
/// @dev Used later to calculate the number of confirmations needed for tx
/// @param _required Number of sigs required
/// @param _count Current number of sigs
function calcConfirmsNeeded(uint _required, uint _count) constant returns (uint){
return _required - _count;
}
/// @dev Used to check if tx is moving tokens and parses amount
/// @param _txData Data for proposed tx
/// @return bool True if transaction is moving tokens
/// @return uint Amount of tokens involved, 0 if not spending tx
function getAmount(bytes _txData) constant returns (bool,uint) {
bytes32 getSig;
bytes4 sig;
bytes4 tSig = 0xa9059cbb; //transfer func signature
bytes4 aSig = 0x095ea7b3; //approve func signature
bytes4 tfSig = 0x23b872dd; //transferFrom func signature
bool transfer;
bytes32 _amountData;
uint _amount;
assembly { getSig := mload(add(_txData,0x20)) }
sig = bytes4(getSig);
if(sig == tSig || sig == aSig){
transfer = true;
assembly { _amountData := mload(add(_txData,0x44)) }
_amount = uint(_amountData);
} else if(sig == tfSig){
transfer = true;
assembly { _amountData := mload(add(_txData,0x64)) }
_amount = uint(_amountData);
}
return (transfer,_amount);
}
/// @dev Retrieves sig requirement for spending tx
/// @param self Contract wallet in storage
/// @param _to Target address of transaction
/// @param _value Amount of ether spend
/// @param _isTransfer True if transferring other tokens, false otherwise
/// @param _amount Amount of tokens being transferred, 0 if not a transfer tx
/// @return uint The required sigs for tx
function getRequired(WalletData storage self,
address _to,
uint _value,
bool _isTransfer,
uint _amount)
returns (uint)
{
bool err;
uint res;
bool major = true;
//Reset spend if this is first check of the day
if((now/ 1 days) > self.currentSpend[0][0]){
self.currentSpend[0][0] = now / 1 days;
self.currentSpend[0][1] = 0;
}
(err, res) = self.currentSpend[0][1].plus(_value);
if(err){
LogErrMsg("Overflow eth spend");
return 0;
}
if(res < self.majorThreshold[0])
major = false;
if(_to != 0 && _isTransfer){
if((now / 1 days) > self.currentSpend[_to][0]){
self.currentSpend[_to][0] = now / 1 days;
self.currentSpend[_to][1] = 0;
}
(err, res) = self.currentSpend[_to][1].plus(_amount);
if(err){
LogErrMsg("Overflow token spend");
return 0;
}
if(res >= self.majorThreshold[_to])
major = true;
}
return major ? self.requiredMajor : self.requiredMinor;
}
/// @dev Function to create new contract
/// @param _txData Transaction data
/// @param _value Amount of eth sending to new contract
function createContract(bytes _txData, uint _value) {
address _newContract;
bool allGood;
assembly {
_newContract := create(_value, add(_txData, 0x20), mload(_txData))
allGood := gt(extcodesize(_newContract),0)
}
require(allGood);
LogContractCreated(_newContract, _value);
}
/*Primary Function*/
/// @dev Create and execute transaction from wallet
/// @param self Wallet in contract storage
/// @param _to Address of target
/// @param _value Amount of ether sending
/// @param _txData Data for executing transaction
/// @param _confirm True if confirming, false if revoking confirmation
/// @param _data Message data passed from wallet contract
/// @return bool Returns true if successful, false otherwise
/// @return bytes32 Returns the tx ID, can be used for confirm/revoke functions
function serveTx(WalletData storage self,
address _to,
uint _value,
bytes _txData,
bool _confirm,
bytes _data)
returns (bool,bytes32)
{
bytes32 _id = sha3("serveTx",_to,_value,_txData);
uint _number = self.transactionInfo[_id].length;
uint _required = self.requiredMajor;
//Run checks if not called from generic confirm/revoke function
if(msg.sender != address(this)){
bool allGood;
uint _amount;
// if the owner is revoking his/her confirmation but doesn't know the
// specific transaction id hash
if(!_confirm) {
allGood = revokeConfirm(self, _id);
return (allGood,_id);
} else { // else confirming the transaction
//if this is a new transaction id or if a previous identical transaction had already succeeded
if(_number == 0 || self.transactionInfo[_id][_number - 1].success){
require(self.ownerIndex[msg.sender] > 0);
//Reuse allGood due to stack limit
if(_to != 0)
(allGood,_amount) = getAmount(_txData);
_required = getRequired(self, _to, _value, allGood,_amount);
if(_required == 0)
return (false, _id);
// add this transaction to the wallets record and initialize the settings
self.transactionInfo[_id].length++;
self.transactionInfo[_id][_number].confirmRequired = _required;
self.transactionInfo[_id][_number].day = now / 1 days;
self.transactions[now / 1 days].push(_id);
} else { // else the transaction is already pending
_number--; // set the index to the index of the existing transaction
//make sure the sender isn't already confirmed
allGood = checkNotConfirmed(self, _id, _number);
if(!allGood)
return (false,_id);
}
}
// add the senders confirmation to the transaction
self.transactionInfo[_id][_number].confirmedOwners.push(uint(msg.sender));
self.transactionInfo[_id][_number].confirmCount++;
}else {
// else were calling from generic confirm/revoke function, set the
// _number index to the index of the existing transaction
_number--;
}
// if there are enough confirmations
if(self.transactionInfo[_id][_number].confirmCount ==
self.transactionInfo[_id][_number].confirmRequired)
{
// execute the transaction
self.currentSpend[0][1] += _value;
self.currentSpend[_to][1] += _amount;
self.transactionInfo[_id][_number].success = true;
if(_to == 0){
//Failure is self contained in method
createContract(_txData, _value);
} else {
require(_to.call.value(_value)(_txData));
}
delete self.transactionInfo[_id][_number].data;
LogTransactionComplete(_id, _to, _value, _data);
} else {
if(self.transactionInfo[_id][_number].data.length == 0)
self.transactionInfo[_id][_number].data = _data;
uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired,
self.transactionInfo[_id][_number].confirmCount);
LogTransactionConfirmed(_id, msg.sender, confirmsNeeded);
}
return (true,_id);
}
/*Confirm/Revoke functions using tx ID*/
/// @dev Confirms a current pending tx, will execute if final confirmation
/// @param self Wallet in contract storage
/// @param _id ID of the transaction
/// @return Returns true if successful, false otherwise
function confirmTx(WalletData storage self, bytes32 _id) returns (bool){
require(self.ownerIndex[msg.sender] > 0);
uint _number = self.transactionInfo[_id].length;
bool ret;
if(_number == 0){
LogErrMsg("Tx not initiated");
LogTransactionFailed(_id, msg.sender);
return false;
}
_number--;
bool allGood = checkNotConfirmed(self, _id, _number);
if(!allGood)
return false;
self.transactionInfo[_id][_number].confirmedOwners.push(uint256(msg.sender));
self.transactionInfo[_id][_number].confirmCount++;
if(self.transactionInfo[_id][_number].confirmCount ==
self.transactionInfo[_id][_number].confirmRequired)
{
address a = address(this);
require(a.call(self.transactionInfo[_id][_number].data));
} else {
uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired,
self.transactionInfo[_id][_number].confirmCount);
LogTransactionConfirmed(_id, msg.sender, confirmsNeeded);
ret = true;
}
return ret;
}
/// @dev Revokes a prior confirmation from sender, call with tx ID
/// @param self Wallet in contract storage
/// @param _id ID of the transaction
/// @return Returns true if successful, false otherwise
function revokeConfirm(WalletData storage self, bytes32 _id)
returns (bool)
{
require(self.ownerIndex[msg.sender] > 0);
uint _number = self.transactionInfo[_id].length;
if(_number == 0){
LogErrMsg("Tx not initiated");
LogTransactionFailed(_id, msg.sender);
return false;
}
_number--;
if(self.transactionInfo[_id][_number].success){
LogErrMsg("Transaction already complete");
LogTransactionFailed(_id, msg.sender);
return false;
}
//Function from Majoolr.io array utility library
bool found;
uint index;
(found, index) = self.transactionInfo[_id][_number].confirmedOwners.indexOf(uint(msg.sender), false);
if(!found){
LogErrMsg("Owner has not confirmed tx");
LogTransactionFailed(_id, msg.sender);
return false;
}
self.transactionInfo[_id][_number].confirmedOwners[index] = 0;
self.transactionInfo[_id][_number].confirmCount--;
uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired,
self.transactionInfo[_id][_number].confirmCount);
//Transaction removed if all sigs revoked but id remains in wallet transaction list
if(self.transactionInfo[_id][_number].confirmCount == 0)
self.transactionInfo[_id].length--;
LogRevokeNotice(_id, msg.sender, confirmsNeeded);
return true;
}
}
pragma solidity ^0.4.13;
/**
* @title Array256 Library
* @author Majoolr.io
*
* version 1.0.0
* Copyright (c) 2017 Majoolr, LLC
* The MIT License (MIT)
* https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE
*
* The Array256 Library provides a few utility functions to work with
* storage uint256[] types in place. Majoolr 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. Majoolr also strives to educate non-profits, schools, and other
* community members about the application of blockchain technology.
* For further information: majoolr.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.
*/
library Array256Lib {
/// @dev Sum vector
/// @param self Storage array containing uint256 type variables
/// @return sum The sum of all elements, does not check for overflow
function sumElements(uint256[] storage self) constant returns(uint256 sum) {
assembly {
mstore(0x60,self_slot)
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
sum := add(sload(add(sha3(0x60,0x20),i)),sum)
}
}
}
/// @dev Returns the max value in an array.
/// @param self Storage array containing uint256 type variables
/// @return maxValue The highest value in the array
function getMax(uint256[] storage self) constant returns(uint256 maxValue) {
assembly {
mstore(0x60,self_slot)
maxValue := sload(sha3(0x60,0x20))
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
switch gt(sload(add(sha3(0x60,0x20),i)), maxValue)
case 1 {
maxValue := sload(add(sha3(0x60,0x20),i))
}
}
}
}
/// @dev Returns the minimum value in an array.
/// @param self Storage array containing uint256 type variables
/// @return minValue The highest value in the array
function getMin(uint256[] storage self) constant returns(uint256 minValue) {
assembly {
mstore(0x60,self_slot)
minValue := sload(sha3(0x60,0x20))
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
switch gt(sload(add(sha3(0x60,0x20),i)), minValue)
case 0 {
minValue := sload(add(sha3(0x60,0x20),i))
}
}
}
}
/// @dev Finds the index of a given value in an array
/// @param self Storage array containing uint256 type variables
/// @param value The value to search for
/// @param isSorted True if the array is sorted, false otherwise
/// @return found True if the value was found, false otherwise
/// @return index The index of the given value, returns 0 if found is false
function indexOf(uint256[] storage self, uint256 value, bool isSorted) constant
returns(bool found, uint256 index) {
assembly{
mstore(0x60,self_slot)
switch isSorted
case 1 {
let high := sub(sload(self_slot),1)
let mid := 0
let low := 0
for { } iszero(gt(low, high)) { } {
mid := div(add(low,high),2)
switch lt(sload(add(sha3(0x60,0x20),mid)),value)
case 1 {
low := add(mid,1)
}
case 0 {
switch gt(sload(add(sha3(0x60,0x20),mid)),value)
case 1 {
high := sub(mid,1)
}
case 0 {
found := 1
index := mid
low := add(high,1)
}
}
}
}
case 0 {
for { let low := 0 } lt(low, sload(self_slot)) { low := add(low, 1) } {
switch eq(sload(add(sha3(0x60,0x20),low)), value)
case 1 {
found := 1
index := low
low := sload(self_slot)
}
}
}
}
}
/// @dev Utility function for heapSort
/// @param index The index of child node
/// @return pI The parent node index
function getParentI(uint256 index) constant private returns (uint256 pI) {
uint256 i = index - 1;
pI = i/2;
}
/// @dev Utility function for heapSort
/// @param index The index of parent node
/// @return lcI The index of left child
function getLeftChildI(uint256 index) constant private returns (uint256 lcI) {
uint256 i = index * 2;
lcI = i + 1;
}
/// @dev Sorts given array in place
/// @param self Storage array containing uint256 type variables
function heapSort(uint256[] storage self) {
uint256 end = self.length - 1;
uint256 start = getParentI(end);
uint256 root = start;
uint256 lChild;
uint256 rChild;
uint256 swap;
uint256 temp;
while(start >= 0){
root = start;
lChild = getLeftChildI(start);
while(lChild <= end){
rChild = lChild + 1;
swap = root;
if(self[swap] < self[lChild])
swap = lChild;
if((rChild <= end) && (self[swap]<self[rChild]))
swap = rChild;
if(swap == root)
lChild = end+1;
else {
temp = self[swap];
self[swap] = self[root];
self[root] = temp;
root = swap;
lChild = getLeftChildI(root);
}
}
if(start == 0)
break;
else
start = start - 1;
}
while(end > 0){
temp = self[end];
self[end] = self[0];
self[0] = temp;
end = end - 1;
root = 0;
lChild = getLeftChildI(0);
while(lChild <= end){
rChild = lChild + 1;
swap = root;
if(self[swap] < self[lChild])
swap = lChild;
if((rChild <= end) && (self[swap]<self[rChild]))
swap = rChild;
if(swap == root)
lChild = end + 1;
else {
temp = self[swap];
self[swap] = self[root];
self[root] = temp;
root = swap;
lChild = getLeftChildI(root);
}
}
}
}
}
pragma solidity ^0.4.13;
/**
* @title Basic Math Library
* @author Majoolr.io
*
* version 1.1.0
* Copyright (c) 2017 Majoolr, LLC
* The MIT License (MIT)
* https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE
*
* The Basic Math Library is inspired by the Safe Math library written by
* OpenZeppelin at https://github.com/OpenZeppelin/zeppelin-solidity/ .
* Majoolr 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. Majoolr
* also strives to educate non-profits, schools, and other community members
* about the application of blockchain technology.
* For further information: majoolr.io, openzeppelin.org
*
* 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.
*/
library BasicMathLib {
event Err(string typeErr);
/// @dev Multiplies two numbers and checks for overflow before returning.
/// Does not throw but rather logs an Err event if there is overflow.
/// @param a First number
/// @param b Second number
/// @return err False normally, or true if there is overflow
/// @return res The product of a and b, or 0 if there is overflow
function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := mul(a,b)
switch or(iszero(b), eq(div(res,b), a))
case 0 {
err := 1
res := 0
}
}
if (err)
Err("times func overflow");
}
/// @dev Divides two numbers but checks for 0 in the divisor first.
/// Does not throw but rather logs an Err event if 0 is in the divisor.
/// @param a First number
/// @param b Second number
/// @return err False normally, or true if `b` is 0
/// @return res The quotient of a and b, or 0 if `b` is 0
function dividedBy(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
switch iszero(b)
case 0 {
res := div(a,b)
mstore(add(mload(0x40),0x20),res)
return(mload(0x40),0x40)
}
}
Err("tried to divide by zero");
return (true, 0);
}
/// @dev Adds two numbers and checks for overflow before returning.
/// Does not throw but rather logs an Err event if there is overflow.
/// @param a First number
/// @param b Second number
/// @return err False normally, or true if there is overflow
/// @return res The sum of a and b, or 0 if there is overflow
function plus(uint256 a, uint256 b) constant returns (bool err, uint256 res) {
assembly{
res := add(a,b)
switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b)))
case 0 {
err := 1
res := 0
}
}
if (err)
Err("plus func overflow");
}
/// @dev Subtracts two numbers and checks for underflow before returning.
/// Does not throw but rather logs an Err event if there is underflow.
/// @param a First number
/// @param b Second number
/// @return err False normally, or true if there is underflow
/// @return res The difference between a and b, or 0 if there is underflow
function minus(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := sub(a,b)
switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1)
case 0 {
err := 1
res := 0
}
}
if (err)
Err("minus func underflow");
}
} | Get sig requirements for minor tx spends self Wallet in contract storage return uint Number of sigs required | function getRequiredMinor(WalletMainLib.WalletData storage self) constant returns (uint) {
return self.requiredMinor;
}
| 2,063,505 |
./full_match/1/0x4e5B0EE20B5d7c7d01cb7f9313bC93d5dB385C73/sources/contracts/vesting/FundsDistributorFactoryA.sol | Withdraw remaining tokens after the cliff period has ended amount Amount of tokens to withdraw/ | function withdrawTokens(uint amount) external onlyOwner returns(bool){
require(block.timestamp > cliff, "FundsDistributorFactoryA::withdrawTokens: cliff period not complete");
IERC20 pushTokenInstance = IERC20(pushToken);
pushTokenInstance.safeTransfer(msg.sender, amount);
return true;
}
| 9,795,914 |
pragma solidity ^0.4.24;
contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = false;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) public onlyOwner {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) public onlyOwner {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) public onlyOwner {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) public onlyOwner {
isMaintaining = _isMaintaining;
}
}
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract EtheremonDataBase {
uint64 public totalMonster;
uint32 public totalClass;
// write
function addElementToArrayType(EtheremonEnum.ArrayType _type, uint64 _id, uint8 _value) external returns(uint);
function addMonsterObj(uint32 _classId, address _trainer, string _name) external returns(uint64);
function removeMonsterIdMapping(address _trainer, uint64 _monsterId) external;
// read
function getElementInArrayType(EtheremonEnum.ArrayType _type, uint64 _id, uint _index) external constant returns(uint8);
function getMonsterClass(uint32 _classId) external constant returns(uint32 classId, uint256 price, uint256 returnPrice, uint32 total, bool catchable);
function getMonsterObj(uint64 _objId) external constant returns(uint64 objId, uint32 classId, address trainer, uint32 exp, uint32 createIndex, uint32 lastClaimIndex, uint createTime);
}
contract EtheremonEnum {
enum ResultCode {
SUCCESS,
ERROR_CLASS_NOT_FOUND,
ERROR_LOW_BALANCE,
ERROR_SEND_FAIL,
ERROR_NOT_TRAINER,
ERROR_NOT_ENOUGH_MONEY,
ERROR_INVALID_AMOUNT
}
enum ArrayType {
CLASS_TYPE,
STAT_STEP,
STAT_START,
STAT_BASE,
OBJ_SKILL
}
enum PropertyType {
ANCESTOR,
XFACTOR
}
}
interface EtheremonMonsterNFTInterface {
function triggerTransferEvent(address _from, address _to, uint _tokenId) external;
function getMonsterCP(uint64 _monsterId) constant external returns(uint cp);
}
contract EtheremonWorldNFT is BasicAccessControl {
uint8 constant public STAT_COUNT = 6;
uint8 constant public STAT_MAX = 32;
struct MonsterClassAcc {
uint32 classId;
uint256 price;
uint256 returnPrice;
uint32 total;
bool catchable;
}
struct MonsterObjAcc {
uint64 monsterId;
uint32 classId;
address trainer;
string name;
uint32 exp;
uint32 createIndex;
uint32 lastClaimIndex;
uint createTime;
}
address public dataContract;
address public monsterNFT;
mapping(uint32 => bool) public classWhitelist;
mapping(address => bool) public addressWhitelist;
uint public gapFactor = 5;
uint public priceIncreasingRatio = 1000;
function setContract(address _dataContract, address _monsterNFT) external onlyModerators {
dataContract = _dataContract;
monsterNFT = _monsterNFT;
}
function setConfig(uint _gapFactor, uint _priceIncreasingRatio) external onlyModerators {
gapFactor = _gapFactor;
priceIncreasingRatio = _priceIncreasingRatio;
}
function setClassWhitelist(uint32 _classId, bool _status) external onlyModerators {
classWhitelist[_classId] = _status;
}
function setAddressWhitelist(address _smartcontract, bool _status) external onlyModerators {
addressWhitelist[_smartcontract] = _status;
}
function mintMonster(uint32 _classId, address _trainer, string _name) external onlyModerators returns(uint) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
// add monster
uint64 objId = data.addMonsterObj(_classId, _trainer, _name);
uint8 value;
uint seed = getRandom(_trainer, block.number-1, objId);
// generate base stat for the previous one
for (uint i=0; i < STAT_COUNT; i += 1) {
seed /= 100;
value = uint8(seed % STAT_MAX) + data.getElementInArrayType(EtheremonEnum.ArrayType.STAT_START, uint64(_classId), i);
data.addElementToArrayType(EtheremonEnum.ArrayType.STAT_BASE, objId, value);
}
EtheremonMonsterNFTInterface(monsterNFT).triggerTransferEvent(address(0), _trainer, objId);
return objId;
}
function burnMonster(uint64 _tokenId) external onlyModerators {
// need to check condition before calling this function
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterObjAcc memory obj;
(obj.monsterId, obj.classId, obj.trainer, obj.exp, obj.createIndex, obj.lastClaimIndex, obj.createTime) = data.getMonsterObj(_tokenId);
require(obj.trainer != address(0));
data.removeMonsterIdMapping(obj.trainer, _tokenId);
EtheremonMonsterNFTInterface(monsterNFT).triggerTransferEvent(obj.trainer, address(0), _tokenId);
}
function catchMonsterNFT(uint32 _classId, string _name) external isActive payable {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
if (class.classId == 0 || class.catchable == false) {
revert();
}
uint price = class.price;
if (class.total > 0)
price += class.price*(class.total-1)/priceIncreasingRatio;
if (msg.value < price) {
revert();
}
// add new monster
uint64 objId = data.addMonsterObj(_classId, msg.sender, _name);
uint8 value;
uint seed = getRandom(msg.sender, block.number-1, objId);
// generate base stat for the previous one
for (uint i=0; i < STAT_COUNT; i += 1) {
seed /= 100;
value = uint8(seed % STAT_MAX) + data.getElementInArrayType(EtheremonEnum.ArrayType.STAT_START, uint64(_classId), i);
data.addElementToArrayType(EtheremonEnum.ArrayType.STAT_BASE, objId, value);
}
EtheremonMonsterNFTInterface(monsterNFT).triggerTransferEvent(address(0), msg.sender, objId);
// refund extra
if (msg.value > price) {
msg.sender.transfer((msg.value - price));
}
}
// for whitelist contracts, no refund extra
function catchMonster(address _player, uint32 _classId, string _name) external isActive payable returns(uint tokenId) {
if (addressWhitelist[msg.sender] == false) {
revert();
}
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
if (class.classId == 0) {
revert();
}
if (class.catchable == false && classWhitelist[_classId] == false) {
revert();
}
uint price = class.price;
if (class.total > gapFactor) {
price += class.price*(class.total - gapFactor)/priceIncreasingRatio;
}
if (msg.value < price) {
revert();
}
// add new monster
uint64 objId = data.addMonsterObj(_classId, _player, _name);
uint8 value;
uint seed = getRandom(_player, block.number-1, objId);
// generate base stat for the previous one
for (uint i=0; i < STAT_COUNT; i += 1) {
seed /= 100;
value = uint8(seed % STAT_MAX) + data.getElementInArrayType(EtheremonEnum.ArrayType.STAT_START, uint64(_classId), i);
data.addElementToArrayType(EtheremonEnum.ArrayType.STAT_BASE, objId, value);
}
EtheremonMonsterNFTInterface(monsterNFT).triggerTransferEvent(address(0), _player, objId);
return objId;
}
function getMonsterClassBasic(uint32 _classId) external constant returns(uint256, uint256, uint256, bool) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
return (class.price, class.returnPrice, class.total, class.catchable);
}
function getPrice(uint32 _classId) external constant returns(bool catchable, uint price) {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
price = class.price;
if (class.total > 0)
price += class.price*(class.total-1)/priceIncreasingRatio;
if (class.catchable == false) {
return (classWhitelist[_classId], price);
} else {
return (true, price);
}
}
// public api
function getRandom(address _player, uint _block, uint _count) public view returns(uint) {
return uint(keccak256(abi.encodePacked(blockhash(_block), _player, _count)));
}
function withdrawEther(address _sendTo, uint _amount) public onlyOwner {
if (_amount > address(this).balance) {
revert();
}
_sendTo.transfer(_amount);
}
}
interface KyberNetworkProxyInterface {
function maxGasPrice() public view returns(uint);
function getUserCapInWei(address user) public view returns(uint);
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
function enabled() public view returns(bool);
function info(bytes32 id) public view returns(uint);
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount,
uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
}
contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
contract Utils2 is Utils {
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(ERC20 token, address user) public view returns(uint) {
if (token == ETH_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function getDecimalsSafe(ERC20 token) internal returns(uint) {
if (decimals[token] == 0) {
setDecimals(token);
}
return decimals[token];
}
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint 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);
}
}
}
interface WrapEtheremonInterface {
/// @notice Can only be called by operators
/// @dev Sets the KyberNetwork address
/// @param _KyberNetwork KyberNetwork contract address
function setKyberNetwork(address _KyberNetwork) public;
/// @dev Get the ETH price of the Etheremon monster and if it is catchable
/// @param _etheremon EtheremonWorldNFT address
/// @param _classId Class ID of monster
/// @param _payPrice Price of monster passed from Etheremon server
/// @return catchable, monsterInETH
function getMonsterPriceInETH(
EtheremonWorldNFT _etheremon,
uint32 _classId,
uint _payPrice
)
public
view
returns (
bool catchable,
uint monsterInETH
);
/// @dev Get the rates of the Etheremon monster
/// @param _kyberProxy KyberNetworkProxyInterface address
/// @param token ERC20 token address
/// @param monsterInETH Price of the monster in ETH
/// @return expectedRate, slippageRate
function getMonsterRates(
KyberNetworkProxyInterface _kyberProxy,
ERC20 token,
uint monsterInETH
)
public
view
returns (
uint expectedRate,
uint slippageRate
);
/// @dev Get the token price and rates of the Etheremon monster
/// @param token ERC20 token address
/// @param expectedRate Expected rate of ETH to token
/// @param monsterInETH Price of the monster in ETH
/// @return monsterInTokens
function getMonsterPriceInTokens(
ERC20 token,
uint expectedRate,
uint monsterInETH
)
public
view
returns (uint monsterInTokens);
/// @dev Acquires the monster from Etheremon using tokens
/// @param _kyberProxy KyberNetworkProxyInterface address
/// @param _etheremon EtheremonWorldNFT address
/// @param _classId Class ID of monster
/// @param _name Name of the monster
/// @param token ERC20 token address
/// @param tokenQty Amount of tokens to be transferred by user
/// @param maxDestQty Actual amount of ETH needed to purchase the monster
/// @param minRate The minimum rate or slippage rate.
/// @param walletId Wallet ID where Kyber referral fees will be sent to
/// @return monsterId
function catchMonster(
KyberNetworkProxyInterface _kyberProxy,
EtheremonWorldNFT _etheremon,
uint32 _classId,
string _name,
ERC20 token,
uint tokenQty,
uint maxDestQty,
uint minRate,
address walletId
)
public
returns (uint monsterId);
}
contract WrapEtheremonPermissions {
event TransferAdmin(address newAdmin);
event OperatorAdded(address newOperator, bool isAdd);
address public admin;
address[] public operatorsGroup;
mapping(address=>bool) internal operators;
uint constant internal MAX_GROUP_SIZE = 50;
constructor () public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdmin(newAdmin);
admin = newAdmin;
}
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]);
require(operatorsGroup.length < MAX_GROUP_SIZE);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
}
contract WrapEtheremon is WrapEtheremonInterface, WrapEtheremonPermissions, Utils2 {
event SwapTokenChange(uint startTokenBalance, uint change);
event CaughtWithToken(address indexed sender, uint monsterId, ERC20 token, uint amount);
event ETHReceived(address indexed sender, uint amount);
address public KyberNetwork;
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
/// @dev Contract contstructor
/// @param _KyberNetwork KyberNetwork main contract address
constructor (address _KyberNetwork) public {
KyberNetwork = _KyberNetwork;
}
/// @dev Return the ETH to user that was taken back by the network
function() public payable {
// Only receive ETH from KyberNetwork main contract
require(msg.sender == KyberNetwork);
emit ETHReceived(msg.sender, msg.value);
}
/// @notice Can only be called by operators
/// @dev Sets the KyberNetwork address
/// @param _KyberNetwork KyberNetwork contract address
function setKyberNetwork(address _KyberNetwork) public onlyOperator {
KyberNetwork = _KyberNetwork;
}
/// @dev Get the ETH price of the Etheremon monster and if it is catchable
/// @param _etheremon EtheremonWorldNFT address
/// @param _classId Class ID of monster
/// @param _payPrice Price of monster passed from Etheremon server
/// @return catchable, monsterInETH
function getMonsterPriceInETH(
EtheremonWorldNFT _etheremon,
uint32 _classId,
uint _payPrice
)
public
view
returns (
bool catchable,
uint monsterInETH
)
{
// Get monster details from Etheremon contract
(catchable, monsterInETH) = _etheremon.getPrice(_classId);
// Get the highest price from contract pricing or offchain pricing
monsterInETH = max(monsterInETH, _payPrice);
return (catchable, monsterInETH);
}
/// @dev Get the rates of the Etheremon monster
/// @param _kyberProxy KyberNetworkProxyInterface address
/// @param token ERC20 token address
/// @param monsterInETH Price of the monster in ETH
/// @return expectedRate, slippageRate
function getMonsterRates(
KyberNetworkProxyInterface _kyberProxy,
ERC20 token,
uint monsterInETH
)
public
view
returns (
uint expectedRate,
uint slippageRate
)
{
// Get the expected and slippage rates of the token to ETH
(expectedRate, slippageRate) = _kyberProxy.getExpectedRate(token, ETH_TOKEN_ADDRESS, monsterInETH);
return (expectedRate, slippageRate);
}
/// @dev Get the token price and rates of the Etheremon monster
/// @param token ERC20 token address
/// @param expectedRate Expected rate of ETH to token
/// @param monsterInETH Price of the monster in ETH
/// @return monsterInTokens
function getMonsterPriceInTokens(
ERC20 token,
uint expectedRate,
uint monsterInETH
)
public
view
returns (uint monsterInTokens)
{
// If expectedRate is 0, return 0 for monster price in tokens
if (expectedRate == 0) {
return 0;
}
// Calculate monster price in tokens
monsterInTokens = calcSrcAmount(ETH_TOKEN_ADDRESS, token, monsterInETH, expectedRate);
return monsterInTokens;
}
/// @dev Acquires the monster from Etheremon using tokens
/// @param _kyberProxy KyberNetworkProxyInterface address
/// @param _etheremon EtheremonWorldNFT address
/// @param _classId Class ID of monster
/// @param _name Name of the monster
/// @param token ERC20 token address
/// @param tokenQty Amount of tokens to be transferred by user
/// @param maxDestQty Actual amount of ETH needed to purchase the monster
/// @param minRate The minimum rate or slippage rate.
/// @param walletId Wallet ID where Kyber referral fees will be sent to
/// @return monsterId
function catchMonster(
KyberNetworkProxyInterface _kyberProxy,
EtheremonWorldNFT _etheremon,
uint32 _classId,
string _name,
ERC20 token,
uint tokenQty,
uint maxDestQty,
uint minRate,
address walletId
)
public
returns (uint monsterId)
{
// Check that the player has transferred the token to this contract
require(token.transferFrom(msg.sender, this, tokenQty));
// Get the starting token balance of the player's wallet
uint startTokenBalance = token.balanceOf(this);
// Mitigate ERC20 Approve front-running attack, by initially setting
// allowance to 0
require(token.approve(_kyberProxy, 0));
// Verify that the token balance has not decreased from front-running
require(token.balanceOf(this) == startTokenBalance);
// Once verified, set the token allowance to tokenQty
require(token.approve(_kyberProxy, tokenQty));
// Swap player's token to ETH to send to Etheremon payments contract
uint userETH = _kyberProxy.tradeWithHint(
token,
tokenQty,
ETH_TOKEN_ADDRESS,
address(this),
maxDestQty,
minRate,
walletId,
""
);
// Acquire the monster and send to player
monsterId = _etheremon.catchMonster.value(userETH)(msg.sender, _classId, _name);
// Log event that monster was caught using tokens
emit CaughtWithToken(msg.sender, monsterId, token, tokenQty);
// Return change to player if any
calcPlayerChange(token, startTokenBalance);
return monsterId;
}
/// @dev Calculates token change and returns to player
/// @param token ERC20 token address
/// @param startTokenBalance Starting token balance of the player's wallet
function calcPlayerChange(ERC20 token, uint startTokenBalance) private {
// Calculate change of player
uint change = token.balanceOf(this);
// Send back change if change is > 0
if (change > 0) {
// Log the exchange event
emit SwapTokenChange(startTokenBalance, change);
// Transfer change back to player
token.transfer(msg.sender, change);
}
}
/// @dev Gets the max between two uint params
/// @param a Param A
/// @param b Param B
/// @return result
function max(uint a, uint b) private pure returns (uint result) {
return a > b ? a : b;
}
} | Acquires the monster from Etheremon using tokens _kyberProxy KyberNetworkProxyInterface address _etheremon EtheremonWorldNFT address _classId Class ID of monster _name Name of the monster token ERC20 token address tokenQty Amount of tokens to be transferred by user maxDestQty Actual amount of ETH needed to purchase the monster minRate The minimum rate or slippage rate. walletId Wallet ID where Kyber referral fees will be sent to return monsterId Check that the player has transferred the token to this contract Get the starting token balance of the player's wallet Mitigate ERC20 Approve front-running attack, by initially setting allowance to 0 Verify that the token balance has not decreased from front-running Once verified, set the token allowance to tokenQty Swap player's token to ETH to send to Etheremon payments contract Acquire the monster and send to player Log event that monster was caught using tokens Return change to player if any | function catchMonster(
KyberNetworkProxyInterface _kyberProxy,
EtheremonWorldNFT _etheremon,
uint32 _classId,
string _name,
ERC20 token,
uint tokenQty,
uint maxDestQty,
uint minRate,
address walletId
)
public
returns (uint monsterId)
{
require(token.transferFrom(msg.sender, this, tokenQty));
uint startTokenBalance = token.balanceOf(this);
require(token.approve(_kyberProxy, 0));
require(token.balanceOf(this) == startTokenBalance);
require(token.approve(_kyberProxy, tokenQty));
uint userETH = _kyberProxy.tradeWithHint(
token,
tokenQty,
ETH_TOKEN_ADDRESS,
address(this),
maxDestQty,
minRate,
walletId,
""
);
monsterId = _etheremon.catchMonster.value(userETH)(msg.sender, _classId, _name);
emit CaughtWithToken(msg.sender, monsterId, token, tokenQty);
calcPlayerChange(token, startTokenBalance);
return monsterId;
}
| 1,045,869 |
// 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.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../libraries/TransferHelper.sol";
import "../libraries/SymbolHelper.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20.sol";
abstract contract AbstractErc20Adapter {
using SymbolHelper for address;
using TransferHelper for address;
/* ========== Storage ========== */
address public underlying;
address public token;
/* ========== Initializer ========== */
function initialize(address _underlying, address _token) public virtual {
require(underlying == address(0) && token == address(0), "initialized");
require(_underlying != address(0) && _token != address(0), "bad address");
underlying = _underlying;
token = _token;
_approve();
}
/* ========== Internal Queries ========== */
function _protocolName() internal view virtual returns (string memory);
/* ========== Metadata ========== */
function name() external view virtual returns (string memory) {
return string(abi.encodePacked(
bytes(_protocolName()),
" ",
bytes(underlying.getSymbol()),
" Adapter"
));
}
function availableLiquidity() public view virtual returns (uint256);
/* ========== Conversion Queries ========== */
function toUnderlyingAmount(uint256 tokenAmount) external view virtual returns (uint256);
function toWrappedAmount(uint256 underlyingAmount) external view virtual returns (uint256);
/* ========== Performance Queries ========== */
function getAPR() public view virtual returns (uint256);
function getHypotheticalAPR(int256 _deposit) external view virtual returns (uint256);
function getRevenueBreakdown()
external
view
virtual
returns (
address[] memory assets,
uint256[] memory aprs
)
{
assets = new address[](1);
aprs = new uint256[](1);
assets[0] = underlying;
aprs[0] = getAPR();
}
/* ========== Caller Balance Queries ========== */
function balanceWrapped() public view virtual returns (uint256) {
return IERC20(token).balanceOf(msg.sender);
}
function balanceUnderlying() external view virtual returns (uint256);
/* ========== Token Actions ========== */
function deposit(uint256 amountUnderlying) external virtual returns (uint256 amountMinted) {
require(amountUnderlying > 0, "deposit 0");
underlying.safeTransferFrom(msg.sender, address(this), amountUnderlying);
amountMinted = _mint(amountUnderlying);
token.safeTransfer(msg.sender, amountMinted);
}
function withdraw(uint256 amountToken) public virtual returns (uint256 amountReceived) {
require(amountToken > 0, "withdraw 0");
token.safeTransferFrom(msg.sender, address(this), amountToken);
amountReceived = _burn(amountToken);
underlying.safeTransfer(msg.sender, amountReceived);
}
function withdrawAll() public virtual returns (uint256 amountReceived) {
return withdraw(balanceWrapped());
}
function withdrawUnderlying(uint256 amountUnderlying) external virtual returns (uint256 amountBurned) {
require(amountUnderlying > 0, "withdraw 0");
amountBurned = _burnUnderlying(amountUnderlying);
underlying.safeTransfer(msg.sender, amountUnderlying);
}
function withdrawUnderlyingUpTo(uint256 amountUnderlying) external virtual returns (uint256 amountReceived) {
require(amountUnderlying > 0, "withdraw 0");
uint256 amountAvailable = availableLiquidity();
amountReceived = amountAvailable < amountUnderlying ? amountAvailable : amountUnderlying;
_burnUnderlying(amountReceived);
underlying.safeTransfer(msg.sender, amountReceived);
}
/* ========== Internal Actions ========== */
function _approve() internal virtual;
/**
* @dev Deposit `amountUnderlying` into the wrapper and return the amount of wrapped tokens received.
* Note:
* - Called after the underlying token is transferred.
* - Should not transfer minted token to caller.
*/
function _mint(uint256 amountUnderlying) internal virtual returns (uint256 amountMinted);
/**
* @dev Burn `amountToken` of `token` and return the amount of `underlying` received.
* Note:
* - Called after the wrapper token is transferred.
* - Should not transfer underlying token to caller.
*/
function _burn(uint256 amountToken) internal virtual returns (uint256 amountReceived);
/**
* @dev Redeem `amountUnderlying` of the underlying token and return the amount of wrapper tokens burned.
* Note:
* - Should transfer the wrapper token from the caller.
* - Should not transfer underlying token to caller.
*/
function _burnUnderlying(uint256 amountUnderlying) internal virtual returns (uint256 amountBurned);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../libraries/TransferHelper.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20.sol";
import "./AbstractErc20Adapter.sol";
abstract contract AbstractEtherAdapter is AbstractErc20Adapter {
using TransferHelper for address;
/* ========== Metadata ========== */
function name() external view virtual override returns (string memory) {
return string(abi.encodePacked(
bytes(_protocolName()),
" ETH Adapter"
));
}
/* ========== Fallback ========== */
fallback() external payable { return; }
receive() external payable { return; }
/* ========== Token Actions ========== */
function deposit(uint256 amountUnderlying)
external
virtual
override
returns (uint256 amountMinted)
{
underlying.safeTransferFrom(msg.sender, address(this), amountUnderlying);
_afterReceiveWETH(amountUnderlying);
amountMinted = _mint(amountUnderlying);
token.safeTransfer(msg.sender, amountMinted);
}
function depositETH() external virtual payable returns (uint256 amountMinted) {
_afterReceiveETH(msg.value);
amountMinted = _mint(msg.value);
token.safeTransfer(msg.sender, amountMinted);
}
function withdraw(uint256 amountToken) public virtual override returns (uint256 amountReceived) {
token.safeTransferFrom(msg.sender, address(this), amountToken);
amountReceived = _burn(amountToken);
_beforeSendWETH(amountReceived);
underlying.safeTransfer(msg.sender, amountReceived);
}
function withdrawAsETH(uint256 amountToken) public virtual returns (uint256 amountReceived) {
token.safeTransferFrom(msg.sender, address(this), amountToken);
amountReceived = _burn(amountToken);
_beforeSendETH(amountReceived);
address(msg.sender).safeTransferETH(amountReceived);
}
function withdrawAllAsETH() public virtual returns (uint256 amountReceived) {
return withdrawAsETH(balanceWrapped());
}
function withdrawUnderlying(uint256 amountUnderlying) external virtual override returns (uint256 amountBurned) {
amountBurned = _burnUnderlying(amountUnderlying);
_beforeSendWETH(amountUnderlying);
underlying.safeTransfer(msg.sender, amountUnderlying);
}
function withdrawUnderlyingAsETH(uint256 amountUnderlying) external virtual returns (uint256 amountBurned) {
amountBurned = _burnUnderlying(amountUnderlying);
_beforeSendETH(amountUnderlying);
address(msg.sender).safeTransferETH(amountUnderlying);
}
function withdrawUnderlyingUpTo(uint256 amountUnderlying) external virtual override returns (uint256 amountReceived) {
require(amountUnderlying > 0, "withdraw 0");
uint256 amountAvailable = availableLiquidity();
amountReceived = amountAvailable < amountUnderlying ? amountAvailable : amountUnderlying;
_burnUnderlying(amountReceived);
_beforeSendWETH(amountReceived);
underlying.safeTransfer(msg.sender, amountReceived);
}
/* ========== Internal Ether Handlers ========== */
// Convert to WETH if contract takes WETH
function _afterReceiveETH(uint256 amount) internal virtual;
// Convert to WETH if contract takes ETH
function _afterReceiveWETH(uint256 amount) internal virtual;
// Convert to ETH if contract returns WETH
function _beforeSendETH(uint256 amount) internal virtual;
// Convert to WETH if contract returns ETH
function _beforeSendWETH(uint256 amount) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../AbstractErc20Adapter.sol";
import "../../interfaces/CompoundInterfaces.sol";
import "../../interfaces/IERC20.sol";
import "../../interfaces/IWETH.sol";
import "../../libraries/LowGasSafeMath.sol";
import "../../libraries/TransferHelper.sol";
import "../../libraries/MinimalSignedMath.sol";
import { CyTokenParams } from "../../libraries/CyTokenParams.sol";
contract CyErc20Adapter is AbstractErc20Adapter() {
using MinimalSignedMath for uint256;
using LowGasSafeMath for uint256;
using TransferHelper for address;
/* ========== Internal Queries ========== */
function _protocolName() internal view virtual override returns (string memory) {
return "IronBank";
}
/* ========== Metadata ========== */
function availableLiquidity() public view override returns (uint256) {
return IERC20(underlying).balanceOf(token);
}
/* ========== Conversion Queries ========== */
function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) {
return (
tokenAmount
.mul(CyTokenParams.currentExchangeRate(token))
/ uint256(1e18)
);
}
function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) {
return underlyingAmount
.mul(1e18)
/ CyTokenParams.currentExchangeRate(token);
}
/* ========== Performance Queries ========== */
function getAPR() public view virtual override returns (uint256) {
return CyTokenParams.getSupplyRate(token, 0);
}
function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) {
return CyTokenParams.getSupplyRate(token, liquidityDelta);
}
/* ========== Caller Balance Queries ========== */
function balanceUnderlying() external view virtual override returns (uint256) {
return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender));
}
/* ========== Internal Actions ========== */
function _approve() internal virtual override {
underlying.safeApproveMax(token);
}
function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) {
address _token = token;
require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed");
amountMinted = IERC20(_token).balanceOf(address(this));
}
function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) {
require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed");
amountReceived = IERC20(underlying).balanceOf(address(this));
}
function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) {
amountBurned = toWrappedAmount(amountUnderlying);
token.safeTransferFrom(msg.sender, address(this), amountBurned);
require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CrErc20: Burn failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../AbstractEtherAdapter.sol";
import "../../interfaces/CompoundInterfaces.sol";
import "../../interfaces/IERC20.sol";
import "../../interfaces/IWETH.sol";
import "../../libraries/LowGasSafeMath.sol";
import "../../libraries/TransferHelper.sol";
import "../../libraries/MinimalSignedMath.sol";
import { CyTokenParams } from "../../libraries/CyTokenParams.sol";
contract CyEtherAdapter is AbstractEtherAdapter() {
using MinimalSignedMath for uint256;
using LowGasSafeMath for uint256;
using TransferHelper for address;
/* ========== Internal Queries ========== */
function _protocolName() internal view virtual override returns (string memory) {
return "IronBank";
}
/* ========== Metadata ========== */
function availableLiquidity() public view override returns (uint256) {
return IERC20(underlying).balanceOf(token);
}
/* ========== Conversion Queries ========== */
function toUnderlyingAmount(uint256 tokenAmount) public view override returns (uint256) {
return (
tokenAmount
.mul(CyTokenParams.currentExchangeRate(token))
/ uint256(1e18)
);
}
function toWrappedAmount(uint256 underlyingAmount) public view override returns (uint256) {
return underlyingAmount
.mul(1e18)
/ CyTokenParams.currentExchangeRate(token);
}
/* ========== Performance Queries ========== */
function getAPR() public view virtual override returns (uint256) {
return CyTokenParams.getSupplyRate(token, 0);
}
function getHypotheticalAPR(int256 liquidityDelta) external view virtual override returns (uint256) {
return CyTokenParams.getSupplyRate(token, liquidityDelta);
}
/* ========== Caller Balance Queries ========== */
function balanceUnderlying() external view virtual override returns (uint256) {
return toUnderlyingAmount(ICToken(token).balanceOf(msg.sender));
}
/* ========== Internal Ether Handlers ========== */
// Convert to WETH if contract takes WETH
function _afterReceiveETH(uint256 amount) internal virtual override {
IWETH(underlying).deposit{value: amount}();
}
// Convert to ETH if contract takes ETH
function _afterReceiveWETH(uint256 amount) internal virtual override {}
// Convert to ETH if contract returns WETH
function _beforeSendETH(uint256 amount) internal virtual override {
IWETH(underlying).withdraw(amount);
}
// Convert to WETH if contract returns ETH
function _beforeSendWETH(uint256 amount) internal virtual override {}
/* ========== Internal Actions ========== */
function _approve() internal virtual override {
underlying.safeApproveMax(token);
}
function _mint(uint256 amountUnderlying) internal virtual override returns (uint256 amountMinted) {
address _token = token;
require(ICToken(_token).mint(amountUnderlying) == 0, "CErc20: Mint failed");
amountMinted = IERC20(_token).balanceOf(address(this));
}
function _burn(uint256 amountToken) internal virtual override returns (uint256 amountReceived) {
require(ICToken(token).redeem(amountToken) == 0, "CErc20: Burn failed");
amountReceived = IERC20(underlying).balanceOf(address(this));
}
function _burnUnderlying(uint256 amountUnderlying) internal virtual override returns (uint256 amountBurned) {
amountBurned = toWrappedAmount(amountUnderlying);
token.safeTransferFrom(msg.sender, address(this), amountBurned);
require(ICToken(token).redeemUnderlying(amountUnderlying) == 0, "CrErc20: Burn failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
pragma abicoder v2;
interface ICToken {
function comptroller() external view returns (address);
function underlying() external view returns (address);
function name() external view returns (string memory);
function totalSupply() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function totalReserves() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function borrowBalanceStored(address account) external view returns (uint);
function interestRateModel() external view returns (IInterestRateModel);
function balanceOf(address account) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint);
function mint(uint256 mintAmount) external returns (uint256);
function mint() external payable;
function redeem(uint256 tokenAmount) external returns (uint256);
function redeemUnderlying(uint256 underlyingAmount) external returns (uint256);
function borrow(uint borrowAmount) external returns (uint);
// Used to check if a cream market is for an SLP token
function sushi() external view returns (address);
}
interface IInterestRateModel {
function getBorrowRate(
uint cash,
uint borrows,
uint reserves
) external view returns (uint);
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint);
}
interface IComptroller {
function admin() external view returns (address);
function _setMintPaused(address cToken, bool state) external returns (bool);
function getAllMarkets() external view returns (ICToken[] memory);
function mintGuardianPaused(address cToken) external view returns (bool);
function compSpeeds(address cToken) external view returns (uint256);
function oracle() external view returns (IPriceOracle);
function compAccrued(address) external view returns (uint);
function markets(address cToken) external view returns (
bool isListed,
uint collateralFactorMantissa,
bool isComped
);
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external;
function refreshCompSpeeds() external;
}
interface IPriceOracle {
function getUnderlyingPrice(address cToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
interface IAdapterRegistry {
/* ========== Events ========== */
event ProtocolAdapterAdded(uint256 protocolId, address protocolAdapter);
event ProtocolAdapterRemoved(uint256 protocolId);
event TokenAdapterAdded(address adapter, uint256 protocolId, address underlying, address wrapper);
event TokenAdapterRemoved(address adapter, uint256 protocolId, address underlying, address wrapper);
event TokenSupportAdded(address underlying);
event TokenSupportRemoved(address underlying);
event VaultFactoryAdded(address factory);
event VaultFactoryRemoved(address factory);
event VaultAdded(address underlying, address vault);
event VaultRemoved(address underlying, address vault);
/* ========== Structs ========== */
struct TokenAdapter {
address adapter;
uint96 protocolId;
}
/* ========== Storage ========== */
function protocolsCount() external view returns (uint256);
function protocolAdapters(uint256 id) external view returns (address protocolAdapter);
function protocolAdapterIds(address protocolAdapter) external view returns (uint256 id);
function vaultsByUnderlying(address underlying) external view returns (address vault);
function approvedVaultFactories(address factory) external view returns (bool approved);
/* ========== Vault Factory Management ========== */
function addVaultFactory(address _factory) external;
function removeVaultFactory(address _factory) external;
/* ========== Vault Management ========== */
function addVault(address vault) external;
function removeVault(address vault) external;
/* ========== Protocol Adapter Management ========== */
function addProtocolAdapter(address protocolAdapter) external returns (uint256 id);
function removeProtocolAdapter(address protocolAdapter) external;
/* ========== Token Adapter Management ========== */
function addTokenAdapter(address adapter) external;
function addTokenAdapters(address[] calldata adapters) external;
function removeTokenAdapter(address adapter) external;
/* ========== Vault Queries ========== */
function getVaultsList() external view returns (address[] memory);
function haveVaultFor(address underlying) external view returns (bool);
/* ========== Protocol Queries ========== */
function getProtocolAdaptersAndIds() external view returns (address[] memory adapters, uint256[] memory ids);
function getProtocolMetadata(uint256 id) external view returns (address protocolAdapter, string memory name);
function getProtocolForTokenAdapter(address adapter) external view returns (address protocolAdapter);
/* ========== Supported Token Queries ========== */
function isSupported(address underlying) external view returns (bool);
function getSupportedTokens() external view returns (address[] memory list);
/* ========== Token Adapter Queries ========== */
function isApprovedAdapter(address adapter) external view returns (bool);
function getAdaptersList(address underlying) external view returns (address[] memory list);
function getAdapterForWrapperToken(address wrapperToken) external view returns (address);
function getAdaptersCount(address underlying) external view returns (uint256);
function getAdaptersSortedByAPR(address underlying)
external
view
returns (address[] memory adapters, uint256[] memory aprs);
function getAdaptersSortedByAPRWithDeposit(
address underlying,
uint256 deposit,
address excludingAdapter
)
external
view
returns (address[] memory adapters, uint256[] memory aprs);
function getAdapterWithHighestAPR(address underlying) external view returns (address adapter, uint256 apr);
function getAdapterWithHighestAPRForDeposit(
address underlying,
uint256 deposit,
address excludingAdapter
) external view returns (address adapter, uint256 apr);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
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 recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
interface IERC20MetadataBytes32 {
function name() external view returns (bytes32);
function symbol() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IErc20Adapter {
/* ========== Metadata ========== */
function underlying() external view returns (address);
function token() external view returns (address);
function name() external view returns (string memory);
function availableLiquidity() external view returns (uint256);
/* ========== Conversion ========== */
function toUnderlyingAmount(uint256 tokenAmount) external view returns (uint256);
function toWrappedAmount(uint256 underlyingAmount) external view returns (uint256);
/* ========== Performance Queries ========== */
function getAPR() external view returns (uint256);
function getHypotheticalAPR(int256 liquidityDelta) external view returns (uint256);
function getRevenueBreakdown()
external
view
returns (
address[] memory assets,
uint256[] memory aprs
);
/* ========== Caller Balance Queries ========== */
function balanceWrapped() external view returns (uint256);
function balanceUnderlying() external view returns (uint256);
/* ========== Interactions ========== */
function deposit(uint256 amountUnderlying) external returns (uint256 amountMinted);
function withdraw(uint256 amountToken) external returns (uint256 amountReceived);
function withdrawAll() external returns (uint256 amountReceived);
function withdrawUnderlying(uint256 amountUnderlying) external returns (uint256 amountBurned);
function withdrawUnderlyingUpTo(uint256 amountUnderlying) external returns (uint256 amountReceived);
}
interface IEtherAdapter is IErc20Adapter {
function depositETH() external payable returns (uint256 amountMinted);
function withdrawAsETH(uint256 amountToken) external returns (uint256 amountReceived);
function withdrawAllAsETH() external returns (uint256 amountReceived);
function withdrawUnderlyingAsETH(uint256 amountUnderlying) external returns (uint256 amountBurned);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../libraries/LowGasSafeMath.sol";
import "../interfaces/ITokenAdapter.sol";
library ArrayHelper {
using EnumerableSet for EnumerableSet.AddressSet;
using LowGasSafeMath for uint256;
/* ========== Type Cast ========== */
/**
* @dev Cast an enumerable address set as an address array.
* The enumerable set library stores the values as a bytes32 array, this function
* casts it as an address array with a pointer assignment.
*/
function toArray(EnumerableSet.AddressSet storage set) internal view returns (address[] memory arr) {
bytes32[] memory bytes32Arr = set._inner._values;
assembly { arr := bytes32Arr }
}
/**
* @dev Cast an array of IErc20Adapter to an array of address using a pointer assignment.
* Note: The resulting array is the same as the original, so all changes to one will be
* reflected in the other.
*/
function toAddressArray(IErc20Adapter[] memory _arr) internal pure returns (address[] memory arr) {
assembly { arr := _arr }
}
/* ========== Math ========== */
/**
* @dev Computes the sum of a uint256 array.
*/
function sum(uint256[] memory arr) internal pure returns (uint256 _sum) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) _sum = _sum.add(arr[i]);
}
/* ========== Removal ========== */
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(uint256[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
uint256 last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(address[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
address last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function mremove(IErc20Adapter[] memory arr, uint256 index) internal pure {
uint256 len = arr.length;
if (index != len - 1) {
IErc20Adapter last = arr[len - 1];
arr[index] = last;
}
assembly { mstore(arr, sub(len, 1)) }
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function remove(bytes32[] storage arr, uint256 index) internal {
uint256 len = arr.length;
if (index == len - 1) {
arr.pop();
return;
}
bytes32 last = arr[len - 1];
arr[index] = last;
arr.pop();
}
/**
* @dev Remove the element at `index` from an array and decrement its length.
* If `index` is the last index in the array, pops it from the array.
* Otherwise, stores the last element in the array at `index` and then pops the last element.
*/
function remove(address[] storage arr, uint256 index) internal {
uint256 len = arr.length;
if (index == len - 1) {
arr.pop();
return;
}
address last = arr[len - 1];
arr[index] = last;
arr.pop();
}
/* ========== Search ========== */
/**
* @dev Find the index of an address in an array.
* If the address is not found, revert.
*/
function indexOf(address[] memory arr, address find) internal pure returns (uint256) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) if (arr[i] == find) return i;
revert("element not found");
}
/**
* @dev Determine whether an element is included in an array.
*/
function includes(address[] memory arr, address find) internal pure returns (bool) {
uint256 len = arr.length;
for (uint256 i; i < len; i++) if (arr[i] == find) return true;
return false;
}
/* ========== Sorting ========== */
/**
* @dev Given an array of tokens and scores, sort by scores in descending order.
* Maintains the relationship between elements of each array at the same index.
*/
function sortByDescendingScore(
address[] memory addresses,
uint256[] memory scores
) internal pure {
uint256 len = addresses.length;
for (uint256 i = 0; i < len; i++) {
uint256 score = scores[i];
address _address = addresses[i];
uint256 j = i - 1;
while (int(j) >= 0 && scores[j] < score) {
scores[j + 1] = scores[j];
addresses[j + 1] = addresses[j];
j--;
}
scores[j + 1] = score;
addresses[j + 1] = _address;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/*
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.
*/
/**
* EIP 1167 Proxy Deployment
* Originally from https://github.com/optionality/clone-factory/
*/
library CloneLibrary {
function getCreateCode(address target) internal pure returns (bytes memory createCode) {
// Reserve 55 bytes for the deploy code + 17 bytes as a buffer to prevent overwriting
// other memory in the final mstore
createCode = new bytes(72);
assembly {
let clone := add(createCode, 32)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), shl(96, target))
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
mstore(createCode, 55)
}
}
function createClone(address target) internal returns (address result) {
bytes memory createCode = getCreateCode(target);
assembly { result := create(0, add(createCode, 32), 55) }
}
function createClone(address target, bytes32 salt) internal returns (address result) {
bytes memory createCode = getCreateCode(target);
assembly { result := create2(0, add(createCode, 32), 55, salt) }
}
function isClone(address target, address query) internal view returns (bool result) {
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), shl(96, target))
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)))
)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../interfaces/CompoundInterfaces.sol";
import "./LowGasSafeMath.sol";
import "./MinimalSignedMath.sol";
library CyTokenParams {
using LowGasSafeMath for uint256;
using MinimalSignedMath for uint256;
uint256 internal constant EXP_SCALE = 1e18;
function getInterestRateParameters(address token) internal view returns (
address model,
uint256 cashPrior,
uint256 borrowsPrior,
uint256 reservesPrior,
uint256 reserveFactorMantissa
) {
ICToken cToken = ICToken(token);
model = address(cToken.interestRateModel());
cashPrior = cToken.getCash();
borrowsPrior = cToken.totalBorrows();
uint256 borrowsPriorForInterestCalculation = borrowsPrior.sub(cToken.borrowBalanceStored(0x560A8E3B79d23b0A525E15C6F3486c6A293DDAd2));
reservesPrior = cToken.totalReserves();
uint256 accrualBlockNumber = cToken.accrualBlockNumber();
uint256 blockDelta = block.number - accrualBlockNumber;
reserveFactorMantissa = cToken.reserveFactorMantissa();
if (blockDelta > 0) {
uint256 borrowRateMantissa = getBorrowRate(address(model), cashPrior, borrowsPriorForInterestCalculation, reservesPrior);
uint256 interestAccumulated = mulScalarTruncate(borrowRateMantissa.mul(blockDelta), borrowsPriorForInterestCalculation);
borrowsPrior = borrowsPrior.add(interestAccumulated);
reservesPrior = mulScalarTruncate(reserveFactorMantissa, interestAccumulated).add(reservesPrior);
}
}
function getSupplyRate(address token, int256 liquidityDelta) internal view returns (uint256) {
(
address model,
uint256 cashPrior,
uint256 borrowsPrior,
uint256 reservesPrior,
uint256 reserveFactorMantissa
) = getInterestRateParameters(token);
return IInterestRateModel(model).getSupplyRate(
cashPrior.add(liquidityDelta),
borrowsPrior,
reservesPrior,
reserveFactorMantissa
).mul(2102400);
}
function currentExchangeRate(address token) internal view returns (uint256 exchangeRate) {
ICToken cToken = ICToken(token);
uint256 blockDelta = block.number - cToken.accrualBlockNumber();
if (blockDelta == 0) {
return cToken.exchangeRateStored();
}
IInterestRateModel model = cToken.interestRateModel();
uint256 cashPrior = cToken.getCash();
uint256 borrowsPrior = cToken.totalBorrows();
uint256 borrowsPriorForInterestCalculation = borrowsPrior.sub(cToken.borrowBalanceStored(0x560A8E3B79d23b0A525E15C6F3486c6A293DDAd2));
uint256 reservesPrior = cToken.totalReserves();
uint256 reserveFactorMantissa = cToken.reserveFactorMantissa();
if (blockDelta > 0) {
uint256 borrowRateMantissa = getBorrowRate(address(model), cashPrior, borrowsPriorForInterestCalculation, reservesPrior);
uint256 interestAccumulated = mulScalarTruncate(borrowRateMantissa.mul(blockDelta), borrowsPriorForInterestCalculation);
borrowsPrior = borrowsPrior.add(interestAccumulated);
reservesPrior = mulScalarTruncate(reserveFactorMantissa, interestAccumulated).add(reservesPrior);
}
return cashPrior.add(borrowsPrior).sub(reservesPrior).mul(1e18) / ICToken(token).totalSupply();
}
function truncate(uint256 x) internal pure returns (uint256) {
return x / EXP_SCALE;
}
function mulScalarTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return truncate(x.mul(y));
}
function mulScalarTruncateAddUInt(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) {
return mulScalarTruncate(x, y).add(z);
}
function getBorrowRate(
address model,
uint256 cash,
uint256 borrows,
uint256 reserves
) internal view returns (uint256 borrowRateMantissa) {
(bool success, bytes memory retData) = model.staticcall(
abi.encodeWithSelector(
IInterestRateModel.getBorrowRate.selector,
cash,
borrows,
reserves
)
);
if (!success) revert(abi.decode(retData, (string)));
assembly {
switch lt(mload(retData), 64)
case 0 {borrowRateMantissa := mload(add(retData, 64))}
default {borrowRateMantissa := mload(add(retData, 32))}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/************************************************************************************************
Originally from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/LowGasSafeMath.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash b83fcf497e895ae59b97c9d04e997023f69b5e97.
Subject to the GPL-2.0 license
*************************************************************************************************/
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) {
require((z = x + y) >= x, errorMessage);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y <= x);
z = x - y;
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) {
require(y <= x, errorMessage);
z = x - y;
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == 0) return 0;
z = x * y;
require(z / x == y);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) {
if (x == 0) return 0;
z = x * y;
require(z / x == y, errorMessage);
}
/// @notice Returns ceil(x / y)
/// @param x The numerator
/// @param y The denominator
/// @return z The quotient of x and y
function divCeil(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x % y == 0 ? x / y : (x/y) + 1;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
library MinimalSignedMath {
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;
}
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;
}
function add(uint256 a, int256 b) internal pure returns (uint256) {
require(a < 2**255);
int256 _a = int256(a);
int256 c = _a + b;
require((b >= 0 && c >= _a) || (b < 0 && c < _a));
if (c < 0) return 0;
return uint256(c);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
import "../interfaces/IERC20Metadata.sol";
library SymbolHelper {
/**
* @dev Returns the index of the lowest bit set in `self`.
* Note: Requires that `self != 0`
*/
function lowestBitSet(uint256 self) internal pure returns (uint256 _z) {
require (self > 0, "Bits::lowestBitSet: Value 0 has no bits set");
uint256 _magic = 0x00818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff;
uint256 val = (self & -self) * _magic >> 248;
uint256 _y = val >> 5;
_z = (
_y < 4
? _y < 2
? _y == 0
? 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100
: 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606
: _y == 2
? 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707
: 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e
: _y < 6
? _y == 4
? 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff
: 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616
: _y == 6
? 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe
: 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd
);
_z >>= (val & 0x1f) << 3;
return _z & 0xff;
}
function getSymbol(address token) internal view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSignature("symbol()"));
if (!success) return "UNKNOWN";
if (data.length != 32) return abi.decode(data, (string));
uint256 symbol = abi.decode(data, (uint256));
if (symbol == 0) return "UNKNOWN";
uint256 emptyBits = 255 - lowestBitSet(symbol);
uint256 size = (emptyBits / 8) + (emptyBits % 8 > 0 ? 1 : 0);
assembly { mstore(data, size) }
return string(data);
}
function getName(address token) internal view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSignature("name()"));
if (!success) return "UNKNOWN";
if (data.length != 32) return abi.decode(data, (string));
uint256 symbol = abi.decode(data, (uint256));
if (symbol == 0) return "UNKNOWN";
uint256 emptyBits = 255 - lowestBitSet(symbol);
uint256 size = (emptyBits / 8) + (emptyBits % 8 > 0 ? 1 : 0);
assembly { mstore(data, size) }
return string(data);
}
function getPrefixedSymbol(string memory prefix, address token) internal view returns (string memory prefixedSymbol) {
prefixedSymbol = string(abi.encodePacked(
prefix,
getSymbol(token)
));
}
function getPrefixedName(string memory prefix, address token) internal view returns (string memory prefixedName) {
prefixedName = string(abi.encodePacked(
prefix,
getName(token)
));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/************************************************************************************************
Originally from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash cfedb1f55864dcf8cc0831fdd8ec18eb045b7fd1.
Subject to the MIT license
*************************************************************************************************/
library TransferHelper {
function safeApproveMax(address token, address to) internal {
safeApprove(token, to, type(uint256).max);
}
function safeUnapprove(address token, address to) internal {
safeApprove(token, to, 0);
}
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes("approve(address,uint256)")));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TH:SA");
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes("transfer(address,uint256)")));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TH:ST");
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TH:STF");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}("");
require(success, "TH:STE");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "../interfaces/IAdapterRegistry.sol";
import "../libraries/CloneLibrary.sol";
import "../libraries/ArrayHelper.sol";
abstract contract AbstractProtocolAdapter {
using ArrayHelper for address[];
/* ========== Events ========== */
event MarketFrozen(address token);
event MarketUnfrozen(address token);
event AdapterFrozen(address adapter);
event AdapterUnfrozen(address adapter);
/* ========== Constants ========== */
/**
* @dev WETH address used for deciding whether to deploy an ERC20 or Ether adapter.
*/
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev Global registry of adapters.
*/
IAdapterRegistry public immutable registry;
/* ========== Storage ========== */
/**
* @dev List of adapters which have been deployed and then frozen.
*/
address[] public frozenAdapters;
/**
* @dev List of tokens which have been frozen and which do not have an adapter.
*/
address[] public frozenTokens;
/**
* @dev Number of tokens which have been mapped by the adapter.
*/
uint256 public totalMapped;
/* ========== Constructor ========== */
constructor(IAdapterRegistry _registry) {
registry = _registry;
}
/* ========== Public Actions ========== */
/**
* @dev Map up to `max` tokens, starting at `totalMapped`.
*/
function map(uint256 max) external virtual {
address[] memory tokens = getUnmappedUpTo(max);
uint256 len = tokens.length;
address[] memory adapters = new address[](len);
uint256 skipped;
for (uint256 i; i < len; i++) {
address token = tokens[i];
if (isTokenMarketFrozen(token)) {
skipped++;
frozenTokens.push(token);
emit MarketFrozen(token);
continue;
}
address adapter = deployAdapter(token);
adapters[i - skipped] = adapter;
}
totalMapped += len;
assembly { if gt(skipped, 0) { mstore(adapters, sub(len, skipped)) } }
registry.addTokenAdapters(adapters);
}
/**
* @dev Unfreeze adapter at `index` in `frozenAdapters`.
* Market for the adapter must not be frozen by the protocol.
*/
function unfreezeAdapter(uint256 index) external virtual {
address adapter = frozenAdapters[index];
require(!isAdapterMarketFrozen(adapter), "Market still frozen");
frozenAdapters.remove(index);
registry.addTokenAdapter(adapter);
emit AdapterUnfrozen(adapter);
}
/**
* @dev Unfreeze token at `index` in `frozenTokens` and create a new adapter for it.
* Market for the token must not be frozen by the protocol.
*/
function unfreezeToken(uint256 index) external virtual {
address token = frozenTokens[index];
require(!isTokenMarketFrozen(token), "Market still frozen");
frozenTokens.remove(index);
address adapter = deployAdapter(token);
registry.addTokenAdapter(adapter);
emit MarketUnfrozen(token);
}
/**
* @dev Freeze `adapter` - add it to `frozenAdapters` and remove it from the registry.
* Does not verify adapter exists or has been registered by this contract because the
* registry handles that.
*/
function freezeAdapter(address adapter) external virtual {
require(isAdapterMarketFrozen(adapter), "Market not frozen");
frozenAdapters.push(adapter);
registry.removeTokenAdapter(adapter);
emit AdapterFrozen(adapter);
}
/* ========== Internal Actions ========== */
/**
* @dev Deploys an adapter for `token`, which will either be an underlying token
* or a wrapper token, whichever is returned by `getUnmapped`.
*/
function deployAdapter(address token) internal virtual returns (address);
/* ========== Public Queries ========== */
/**
* @dev Name of the protocol the adapter is for.
*/
function protocol() external view virtual returns (string memory);
/**
* @dev Get the list of tokens which have not already been mapped by the adapter.
* Tokens may be underlying tokens or wrapper tokens for a lending market.
*/
function getUnmapped() public view virtual returns (address[] memory tokens);
/**
* @dev Get up to `max` tokens which have not already been mapped by the adapter.
* Tokens may be underlying tokens or wrapper tokens for a lending market.
*/
function getUnmappedUpTo(uint256 max) public view virtual returns (address[] memory tokens) {
tokens = getUnmapped();
if (tokens.length > max) {
assembly { mstore(tokens, max) }
}
}
function getFrozenAdapters() external view returns (address[] memory tokens) {
tokens = frozenAdapters;
}
function getFrozenTokens() external view returns (address[] memory tokens) {
tokens = frozenTokens;
}
/* ========== Internal Queries ========== */
/**
* @dev Check whether the market for an adapter is frozen.
*/
function isAdapterMarketFrozen(address adapter) internal view virtual returns (bool);
/**
* @dev Check whether the market for a token is frozen.
*/
function isTokenMarketFrozen(address token) internal view virtual returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "../interfaces/CompoundInterfaces.sol";
import "../adapters/ironbank/CyErc20Adapter.sol";
import "../adapters/ironbank/CyEtherAdapter.sol";
import "./AbstractProtocolAdapter.sol";
contract IronBankProtocolAdapter is AbstractProtocolAdapter {
using CloneLibrary for address;
/* ========== Constants ========== */
IComptroller public constant comptroller = IComptroller(0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB);
address public immutable erc20AdapterImplementation;
address public immutable etherAdapterImplementation;
/* ========== Constructor ========== */
constructor(IAdapterRegistry _registry) AbstractProtocolAdapter(_registry) {
erc20AdapterImplementation = address(new CyErc20Adapter());
etherAdapterImplementation = address(new CyEtherAdapter());
}
/* ========== Internal Actions ========== */
function deployAdapter(address cToken) internal virtual override returns (address adapter) {
address underlying;
// The call to underlying will use all the gas sent if it fails,
// so we specify a maximum of 25k gas. The contract will only use ~2k
// but this protects against all likely changes to the gas schedule.
try ICToken(cToken).underlying{gas: 25000}() returns (address _underlying) {
underlying = _underlying;
if (underlying == address(0)) {
underlying = weth;
}
} catch {
underlying = weth;
}
if (underlying == weth) {
adapter = CloneLibrary.createClone(etherAdapterImplementation);
} else {
adapter = CloneLibrary.createClone(erc20AdapterImplementation);
}
CyErc20Adapter(adapter).initialize(underlying, address(cToken));
}
/* ========== Public Queries ========== */
function protocol() external pure virtual override returns (string memory) {
return "Iron Bank";
}
function getUnmapped() public view virtual override returns (address[] memory cTokens) {
cTokens = toAddressArray(comptroller.getAllMarkets());
uint256 len = cTokens.length;
uint256 prevLen = totalMapped;
if (len == prevLen) {
assembly { mstore(cTokens, 0) }
} else {
assembly {
cTokens := add(cTokens, mul(prevLen, 32))
mstore(cTokens, sub(len, prevLen))
}
}
}
function toAddressArray(ICToken[] memory cTokens) internal pure returns (address[] memory arr) {
assembly { arr := cTokens }
}
/* ========== Internal Queries ========== */
function isAdapterMarketFrozen(address adapter) internal view virtual override returns (bool) {
return isTokenMarketFrozen(IErc20Adapter(adapter).token());
}
function isTokenMarketFrozen(address cToken) internal view virtual override returns (bool) {
if (comptroller.mintGuardianPaused(cToken)) {
return true;
}
return IERC20(cToken).totalSupply() == 0;
}
}
| SPDX-License-Identifier: MIT | interface IWETH {
function deposit() external payable;
function withdraw(uint) external;
}
| 14,728,137 |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract BTRST {
/// @notice EIP-20 token name for this token
string public constant name = "BTRST";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "BTRST";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 250000000e18; // 250 million BTRST
/// @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 A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice 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 BTRST token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "BTRST::transfer: 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, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "BTRST::transferFrom: 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, uint nonce, uint 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), "BTRST::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BTRST::delegateBySig: invalid nonce");
require(now <= expiry, "BTRST::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (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, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "BTRST::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
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), "BTRST::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "BTRST::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "BTRST::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "BTRST::_transferTokens: 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, "BTRST::_moveVotes: 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, "BTRST::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "BTRST::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint 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 pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/ | function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "BTRST::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
| 6,694,443 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../credit/CreditSystem.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "./GenericLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
bool isActive = reserve.getActive();
require(amount != 0, "VL_INVALID_AMOUNT");
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData
) external view {
require(amount != 0, "VL_INVALID_AMOUNT");
require(amount <= userBalance, "VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE");
bool isActive = reservesData[reserveAddress].getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
}
struct ValidateBorrowLocalVars {
uint256 userBorrowBalance;
uint256 availableLiquidity;
bool isActive;
}
/**
* @dev Validates a borrow action
* @param availableBorrowsInWEI available borrows in WEI
* @param reserve The reserve state from which the user is borrowing
* @param amount The amount to be borrowed
*/
function validateBorrow(
uint256 availableBorrowsInWEI,
DataTypes.ReserveData storage reserve,
uint256 amount
) external view {
ValidateBorrowLocalVars memory vars;
require(availableBorrowsInWEI > 0, "available credit line not enough");
uint256 decimals_ = 1 ether;
uint256 borrowsAmountInWEI = amount.div(10**reserve.decimals).mul(uint256(decimals_));
require(borrowsAmountInWEI <= availableBorrowsInWEI, "borrows exceed credit line");
vars.isActive = reserve.getActive();
require(vars.isActive, "VL_NO_ACTIVE_RESERVE");
require(amount > 0, "VL_INVALID_AMOUNT");
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or type(uint256).min
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
address onBehalfOf,
uint256 variableDebt
) external view {
bool isActive = reserve.getActive();
require(isActive, "VL_NO_ACTIVE_RESERVE");
require(amountSent > 0, "VL_INVALID_AMOUNT");
require(variableDebt > 0, "VL_NO_DEBT_OF_SELECTED_TYPE");
require(
amountSent != type(uint256).max || msg.sender == onBehalfOf,
"VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "../interfaces/IVariableDebtToken.sol";
import "../interfaces/IReserveInterestRateStrategy.sol";
import "./MathUtils.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "../interfaces/IKToken.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/**
* @title ReserveLogic library
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
using ReserveLogic for DataTypes.ReserveData;
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param kTokenAddress The address of the overlying ktoken contract
* @param variableDebtTokenAddress The address of the variable debt token
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address kTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress
) external {
require(reserve.kTokenAddress == address(0), "the reserve already initialized");
reserve.isActive = true;
reserve.liquidityIndex = uint128(KyokoMath.ray());
reserve.variableBorrowIndex = uint128(KyokoMath.ray());
reserve.kTokenAddress = kTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex
);
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
* @param timestamp The last operate time of reserve
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
// 1 + ratePerSecond * (delta_t / seconds in a year)
uint256 cumulatedLiquidityInterest =
MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, "RL_LIQUIDITY_INDEX_OVERFLOW");
reserve.liquidityIndex = uint128(newLiquidityIndex);
//we need to ensure that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(
newVariableBorrowIndex <= type(uint128).max,
"RL_VARIABLE_BORROW_INDEX_OVERFLOW"
);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
struct MintToTreasuryLocalVars {
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint16 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex
) internal {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = getReserveFactor(reserve);
if (vars.reserveFactor == 0) {
return;
}
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars
.currentVariableDebt
.sub(vars.previousVariableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IKToken(reserve.kTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 newLiquidityRate;
uint256 newVariableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address kTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
(
vars.newLiquidityRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
kTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalVariableDebt,
getReserveFactor(reserve)
);
require(vars.newLiquidityRate <= type(uint128).max, "RL_LIQUIDITY_RATE_OVERFLOW");
require(vars.newVariableRate <= type(uint128).max, "RL_VARIABLE_BORROW_RATE_OVERFLOW");
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated =
MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveData storage self, bool active) internal {
self.isActive = active;
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveData storage self) internal view returns (bool) {
return self.isActive;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor)
internal
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR");
self.factor = reserveFactor;
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveData storage self)
internal
view
returns (uint16)
{
return self.factor;
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimal(DataTypes.ReserveData storage self)
internal
view
returns (uint8)
{
return self.decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title PercentageMath library
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./KyokoMath.sol";
library MathUtils {
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(KyokoMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return KyokoMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return KyokoMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library KyokoMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, "MATH_MULTIPLICATION_OVERFLOW");
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW");
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, "MATH_ADDITION_OVERFLOW");
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, "MATH_MULTIPLICATION_OVERFLOW");
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
import "./KyokoMath.sol";
import "./PercentageMath.sol";
import "./ReserveLogic.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMathUpgradeable for uint256;
using KyokoMath for uint256;
using PercentageMath for uint256;
struct CalculateUserAccountDataVars {
uint256 decimals;
uint256 tokenUnit;
uint256 compoundedBorrowBalance;
uint256 totalDebtInWEI;
uint256 i;
address currentReserveAddress;
}
/**
* @dev Calculates the user total Debt in WEI across the reserves.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param reserves The list of the available reserves
* @param reservesCount the count of reserves
* @return The total debt of the user in WEI
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
mapping(uint256 => address) storage reserves,
uint256 reservesCount
)
internal
view
returns (uint256)
{
CalculateUserAccountDataVars memory vars;
for (vars.i = 0; vars.i < reservesCount; vars.i++) {
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
vars.decimals = currentReserve.getDecimal();
uint256 decimals_ = 1 ether;
vars.tokenUnit = uint256(decimals_).div(10**vars.decimals);
uint256 currentReserveBorrows = IERC20Upgradeable(currentReserve.variableDebtTokenAddress).balanceOf(user);
if (currentReserveBorrows > 0) {
vars.totalDebtInWEI = vars.totalDebtInWEI.add(
uint256(1).mul(currentReserveBorrows).mul(vars.tokenUnit)
);
}
}
return vars.totalDebtInWEI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library DataTypes {
struct ReserveData {
//this current state of the asset;
bool isActive;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the last update time of the reserve
uint40 lastUpdateTimestamp;
//address of the ktoken
address kTokenAddress;
//address of the debt token
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
// Reserve factor
uint16 factor;
uint8 decimals;
//the id of the reserve.Represents the position in the list of the active reserves.
uint8 id;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./IScaledBalanceToken.sol";
import "./IInitializableDebtToken.sol";
interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address kToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../lendingpool/DataTypes.sol";
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the kTokens
* @param amount The amount deposited
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of kTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRate The numeric rate at which the user has borrowed
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRate
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on initReserve()
**/
event InitReserve(
address asset,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Emitted when a reserve factor is updated
* @param asset The address of the underlying asset of the reserve
* @param factor The new reserve factor
**/
event ReserveFactorChanged(address indexed asset, uint256 factor);
/**
* @dev Emitted when a reserve active state is updated
* @param asset The address of the underlying asset of the reserve
* @param active The new reserve active state
**/
event ReserveActiveChanged(address indexed asset, bool active);
/**
* @dev Emitted when credit system is updated
* @param creditContract The address of the new credit system
**/
event CreditStrategyChanged(address creditContract);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying kTokens.
* - E.g. User deposits 100 USDT and gets in return 100 kUSDT
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the kTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of kTokens
* is a different wallet
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned
* E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 aUSDT
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole kToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already had a credit line, or he was given enough allowance by a credit delegator on the
* corresponding debt token
* - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet
* and 100 variable debt tokens
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own credit, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDT, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset`
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
address onBehalfOf
) external returns (uint256);
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalDebtInWEI the total debt in WEI of the user
* @return availableBorrowsInWEI the borrowing power left of the user
**/
function getUserAccountData(address user)
external
view
returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI);
function initReserve(
address reserve,
address kTokenAddress,
address variableDebtAddress,
address interestRateStrategyAddress,
uint8 reserveDecimals,
uint16 reserveFactor
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function setPause(bool val) external;
function paused() external view returns (bool);
function getActive(address asset) external view returns (bool);
function setCreditStrategy(address creditContract) external;
function getCreditStrategy() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./IScaledBalanceToken.sol";
import "./IInitializableKToken.sol";
interface IKToken is IERC20Upgradeable, IScaledBalanceToken, IInitializableKToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` kTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after kTokens are burned
* @param from The owner of the kTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns kTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the kTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints kTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Invoked to execute actions on the kToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the underlying asset of this kToken (E.g. USDT for kUSDT)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableKToken {
/**
* @dev Emitted when an kToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param kTokenDecimals the decimals of the underlying
* @param kTokenName the name of the kToken
* @param kTokenSymbol the symbol of the kToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
uint8 kTokenDecimals,
string kTokenName,
string kTokenSymbol,
bytes params
);
/**
* @dev Initializes the kToken
* @param pool The address of the lending pool where this kToken will be used
* @param treasury The address of the Kyoko treasury, receiving the fees on this kToken
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param kTokenDecimals The decimals of the kToken, same as the underlying asset's
* @param kTokenName The name of the kToken
* @param kTokenSymbol The symbol of the kToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
uint8 kTokenDecimals,
string calldata kTokenName,
string calldata kTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ILendingPool.sol";
interface IInitializableDebtToken {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this kToken will be used
* @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT)
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
/**
* @dev this contract represents the credit line in the whitelist.
* @dev the guild's credit line amount
* @dev the decimals is 1e18.
*/
contract CreditSystem is AccessControlEnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// the role manage total credit manager
bytes32 public constant ROLE_CREDIT_MANAGER =
keccak256("ROLE_CREDIT_MANAGER");
uint8 public constant G2G_MASK = 0x0E;
uint8 public constant CCAL_MASK = 0x0D;
uint8 constant IS_G2G_START_BIT_POSITION = 0;
uint8 constant IS_CCAL_START_BIT_POSITION = 1;
struct CreditInfo {
//ERC20 credit line
uint256 g2gCreditLine;
//ccal module credit line
uint256 ccalCreditLine;
//bit 0: g2g isActive flag(0==false, 1==true)
//bit 1: ccal isActive flag(0==false, 1==true)
uint8 flag;
}
// the credit line
mapping(address => CreditInfo) whiteList;
//g2g whiteList Set
EnumerableSetUpgradeable.AddressSet private g2gWhiteSet;
//ccal whiteList Set
EnumerableSetUpgradeable.AddressSet private ccalWhiteSet;
event SetG2GCreditLine(address user, uint256 amount);
event SetCCALCreditLine(address user, uint256 amount);
// event SetPaused(address user, bool flag);
event SetG2GActive(address user, bool active);
event SetCCALActive(address user, bool active);
event RemoveG2GCredit(address user);
event RemoveCCALCredit(address user);
modifier onlyCreditManager() {
require(
hasRole(ROLE_CREDIT_MANAGER, _msgSender()),
"only the manager has permission to perform this operation."
);
_;
}
// constructor() {
// _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
// }
function initialize() public initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* set the address's g2g module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setG2GCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].g2gCreditLine = amount;
setG2GActive(user, amount > 0);
emit SetG2GCreditLine(user, amount);
}
/**
* @dev set the address's g2g module credit active status
*/
function setG2GActive(address user, bool active) public onlyCreditManager {
//set user flag
setG2GFlag(user, active);
//set user white set
if (active) {
uint256 userG2GCreditLine = getG2GCreditLine(user);
userG2GCreditLine > 0 ? g2gWhiteSet.add(user) : g2gWhiteSet.remove(user);
} else {
g2gWhiteSet.remove(user);
}
emit SetG2GActive(user, active);
}
function setG2GFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & G2G_MASK) |
(uint8(active ? 1 : 0) << IS_G2G_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* set the address's ccal module credit line
* @dev user the guild in the whiteList
* @dev amount the guild credit line amount
* @dev 1U = 1e18
*/
function setCCALCreditLine(address user, uint256 amount)
public
onlyCreditManager
{
whiteList[user].ccalCreditLine = amount;
setCCALActive(user, amount > 0);
emit SetCCALCreditLine(user, amount);
}
/**
* @dev set the address's ccal module credit active status
*/
function setCCALActive(address user, bool active) public onlyCreditManager {
//set user flag
setCCALFlag(user, active);
//set user white set
if (active) {
uint256 userCCALCreditLine = getCCALCreditLine(user);
userCCALCreditLine > 0 ? ccalWhiteSet.add(user) : ccalWhiteSet.remove(user);
} else {
ccalWhiteSet.remove(user);
}
emit SetCCALActive(user, active);
}
function setCCALFlag(address user, bool active) private {
uint8 flag = whiteList[user].flag;
flag =
(flag & CCAL_MASK) |
(uint8(active ? 1 : 0) << IS_CCAL_START_BIT_POSITION);
whiteList[user].flag = flag;
}
/**
* remove the address's g2g module credit line
*/
function removeG2GCredit(address user) public onlyCreditManager {
whiteList[user].g2gCreditLine = 0;
setG2GActive(user, false);
emit RemoveG2GCredit(user);
}
/**
* remove the address's ccal module credit line
*/
function removeCCALCredit(address user) public onlyCreditManager {
whiteList[user].ccalCreditLine = 0;
setCCALActive(user, false);
emit RemoveCCALCredit(user);
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return G2G credit line
*/
function getG2GCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.g2gCreditLine;
}
/**
* @dev query the user credit line
* @param user the address which to query
* @return CCAL credit line
*/
function getCCALCreditLine(address user) public view returns (uint256) {
CreditInfo memory credit = whiteList[user];
return credit.ccalCreditLine;
}
/**
* @dev query the white list addresses in G2G
*/
function getG2GWhiteList() public view returns (address[] memory) {
return g2gWhiteSet.values();
}
/**
* @dev query the white list addresses in CCAL
*/
function getCCALWhiteList() public view returns (address[] memory) {
return ccalWhiteSet.values();
}
/**
* @dev query the address state
*/
function getState(address user) public view returns (bool, bool) {
uint8 activeFlag = whiteList[user].flag;
return (
activeFlag & ~G2G_MASK != 0,
activeFlag & ~CCAL_MASK != 0
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 EnumerableSetUpgradeable {
// 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 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 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) {
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 (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 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
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @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/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_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 {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^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 {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 initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
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() {
// 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, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// 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 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
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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 v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
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(IAccessControlUpgradeable).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 ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.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 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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).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) 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);
}
uint256[49] private __gap;
} | Sets the reserve factor of the reserve self The reserve configuration reserveFactor The reserve factor/ | function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor)
internal
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR");
self.factor = reserveFactor;
}
| 11,804,919 |
pragma solidity >=0.4.24;
import "./Store.sol";
import "../modules/Ownable.sol";
import "../libraries/AddressUtils.sol";
///@title Governance means to govern the protocol well.
contract Governance is Ownable, Store {
using AddressUtils for address;
//relayers of the contract
mapping(address => bool) public relayers;
//whether is paused
bool public paused = false;
//token registered map from baseToken->quoteToken->true/false
mapping(address => mapping(address => bool))public tokenRegistered;
event RelayerChanged(address indexed _relayer, bool _bool);
event TokenRegistered(address indexed _base, address indexed _quote);
///modifiers
///check only relayer
modifier onlyRelayer {
require(relayers[msg.sender], "only relayer allowed");
_;
}
///check is paused
modifier notPaused {
require(!paused, "contract is paused");
_;
}
///check trade token is registered
modifier isRegistered(address _base, address _quote){
require(tokenRegistered[_base][_quote], "token not registered");
_;
}
/**
* @dev set the relayer of the contract.
* @param _relayer relayer address
* @param _bool boolean to indicate that the relayer is enabled.
*/
function setRelayer(address _relayer, bool _bool) public onlyOwner {
require(_relayer != ETH_ADDRESS, "relayer should not be 0x0 address.");
relayers[_relayer] = _bool;
emit RelayerChanged(_relayer, _bool);
}
/**
* @dev modify the block number of withdraw to wait.
* @param _number block number to wait
*/
function modifyWithdrawBlock(uint256 _number) public onlyOwner {
require(_number >= 1, "block number to wait should be >=1.");
WITHDRAW_BLOCK_NUM = _number;
}
/**
* @dev pause this contract to fill order when emergency.
**/
function pause() public onlyOwner {
paused = true;
}
/**
* @dev register token as trade pair.only owner allowed.
* @param _base base token of trade pair.0 is ETH
* @param _quote quote token.
**/
function registerToken(address _base, address _quote) public onlyOwner {
require(_quote.isContract(), "quote token is not contract");
require(_base.isZero() || _base.isContract(), "quote token is not contract");
if (!tokenRegistered[_base][_quote]) {
tokenRegistered[_base][_quote] = true;
emit TokenRegistered(_base, _quote);
}
}
}
| modify the block number of withdraw to wait. _number block number to wait/ | function modifyWithdrawBlock(uint256 _number) public onlyOwner {
require(_number >= 1, "block number to wait should be >=1.");
WITHDRAW_BLOCK_NUM = _number;
}
| 13,018,730 |
pragma solidity ^0.4.21;
import "./Ownable.sol";
/**
* Escrow smart contract serves 3 parties.
*
* Judge = is able to move funds to flexiana or customer.
* Customer = Flexiana's client
* Flexiana = we
*
* After creating contract, setAddressesOnce() have to be called.
*
* @author Jiri Knesl <[email protected]>
*/
contract Escrow is Ownable
{
/*** SECTION: Internal state & modifiers */
enum Statuses {DoNothing, ShouldTransferToCustomer, ShouldTransferToFlexiana}
bool public addressChanged = false;
address public customer;
address public flexiana;
// address public owner; // owner = independent judge
Escrow.Statuses public customerStatus = Statuses.DoNothing;
Escrow.Statuses public flexianaStatus = Statuses.DoNothing;
modifier onlyCustomer() {
require(msg.sender == customer);
_;
}
modifier onlyFlexiana() {
require(msg.sender == flexiana);
_;
}
/*** SECTION: Initialization */
/**
* After intitialization setAddressesOnce is called with all members addresses.
* This method can be called only once and only by contract creator.
*/
function setAddressesOnce(address judge, address newFlexiana, address newCustomer) public onlyOwner {
require(! addressChanged);
addressChanged = true;
owner = judge;
flexiana = newFlexiana;
customer = newCustomer;
}
/*** SECTION: Changing customer status */
function changeCustomerStatus(Escrow.Statuses newStatus) internal onlyCustomer {
customerStatus = newStatus;
}
/**
* Called when customer wants funds to stay in the Escrow
*/
function changeCustomerStatusToDoNothing() public onlyCustomer {
changeCustomerStatus(Statuses.DoNothing);
}
/**
* Called when customer wants to return funds back.
*/
function changeCustomerStatusToShouldTransferToCustomer() public onlyCustomer {
changeCustomerStatus(Statuses.ShouldTransferToCustomer);
}
/**
* Called when customer wants to transfer funds to flexiana.
*/
function changeCustomerStatusToShouldTransferToFlexiana() public onlyCustomer {
changeCustomerStatus(Statuses.ShouldTransferToFlexiana);
}
/*** SECTION: Changing Flexiana status */
function changeFlexianaStatus(Escrow.Statuses newStatus) internal onlyFlexiana {
flexianaStatus = newStatus;
}
/**
* Flexiana wants to hold funds in the escrow.
*/
function changeFlexianaStatusToDoNothing() public onlyFlexiana {
changeFlexianaStatus(Statuses.DoNothing);
}
/**
* Flexiana wants to send funds back to customer.
*/
function changeFlexianaStatusToShouldTransferToCustomer() public onlyFlexiana {
changeFlexianaStatus(Statuses.ShouldTransferToCustomer);
}
/**
* Client wants to return money.
*/
function changeFlexianaStatusToShouldTransferToFlexiana() public onlyFlexiana {
changeFlexianaStatus(Statuses.ShouldTransferToFlexiana);
}
/*** SECTION: Deposits */
/**
* Let's save amount in smart contract.
*/
function deposit() public payable {
}
/**
* Safer way how to store funds. It requires only customer to deposit funds.
*/
function customerDeposit() public payable onlyCustomer {
}
/*** SECTION: Transfers */
/**
* If Flexiana agrees or if judge decides, funds are transfered do customer.
*/
function transferToCustomer() public {
require(flexianaStatus == Statuses.ShouldTransferToCustomer || msg.sender == owner);
customer.transfer(address(this).balance);
}
/**
* If client agrees or if judge decides, funds are transfered to flexiana.
*/
function transferToFlexiana() public {
require(customerStatus == Statuses.ShouldTransferToCustomer || msg.sender == owner);
flexiana.transfer(address(this).balance);
}
/**
* Withdraw funds to party that should have funds.
*/
function withdraw() public {
require(flexianaStatus != Statuses.DoNothing && flexianaStatus == customerStatus);
require(msg.sender == owner || msg.sender == flexiana || msg.sender == customer);
if (flexianaStatus == Statuses.ShouldTransferToCustomer) {
customer.transfer(address(this).balance);
} else if (flexianaStatus == Statuses.ShouldTransferToFlexiana) {
flexiana.transfer(address(this).balance);
}
}
} | If client agrees or if judge decides, funds are transfered to flexiana./ | function transferToFlexiana() public {
require(customerStatus == Statuses.ShouldTransferToCustomer || msg.sender == owner);
flexiana.transfer(address(this).balance);
}
| 14,084,722 |
// SPDX-License-Identifier: Unlicense
// solhint-disable var-name-mixedcase
pragma solidity >=0.8.4;
import "./ERC20.sol";
import "./IERC20Permit.sol";
/// @title ERC20Permit
/// @author Paul Razvan Berg
contract ERC20Permit is
IERC20Permit, // one dependency
ERC20 // one dependency
{
/// PUBLIC STORAGE ///
/// @inheritdoc IERC20Permit
bytes32 public immutable override DOMAIN_SEPARATOR;
/// @inheritdoc IERC20Permit
bytes32 public constant override PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @inheritdoc IERC20Permit
mapping(address => uint256) public override nonces;
/// @inheritdoc IERC20Permit
string public constant override version = "1";
/// CONSTRUCTOR ///
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20(_name, _symbol, _decimals) {
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(version)),
chainId,
address(this)
)
);
}
/// PUBLIC NON-CONSTANT FUNCTIONS ///
/// @inheritdoc IERC20Permit
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override {
if (owner == address(0)) {
revert ERC20Permit__OwnerZeroAddress();
}
if (spender == address(0)) {
revert ERC20Permit__SpenderZeroAddress();
}
if (deadline < block.timestamp) {
revert ERC20Permit__PermitExpired(deadline);
}
// It's safe to use unchecked here because the nonce cannot realistically overflow, ever.
bytes32 hashStruct;
unchecked {
hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
}
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct));
address recoveredOwner = ecrecover(digest, v, r, s);
if (recoveredOwner == address(0)) {
revert ERC20Permit__RecoveredOwnerZeroAddress();
}
if (recoveredOwner != owner) {
revert ERC20Permit__InvalidSignature(v, r, s);
}
approveInternal(owner, spender, value);
}
}
| @inheritdoc IERC20Permit | function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override {
if (owner == address(0)) {
revert ERC20Permit__OwnerZeroAddress();
}
if (spender == address(0)) {
revert ERC20Permit__SpenderZeroAddress();
}
if (deadline < block.timestamp) {
revert ERC20Permit__PermitExpired(deadline);
}
unchecked {
hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
}
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct));
address recoveredOwner = ecrecover(digest, v, r, s);
if (recoveredOwner == address(0)) {
revert ERC20Permit__RecoveredOwnerZeroAddress();
}
if (recoveredOwner != owner) {
revert ERC20Permit__InvalidSignature(v, r, s);
}
approveInternal(owner, spender, value);
}
| 949,130 |
pragma solidity ^0.4.15;
/**
* @title DirectCrowdsaleLib
* @author Majoolr.io
*
* version 1.0.0
* Copyright (c) 2017 Majoolr, LLC
* The MIT License (MIT)
* https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE
*
* The DirectCrowdsale Library provides functionality to create a initial coin offering
* for a standard token sale with high supply where there is a direct ether to
* token transfer.
*
* Majoolr provides smart contract services and security reviews for contract
* deployments in addition to working on open source projects in the Ethereum
* community. Our purpose is to test, document, and deploy reusable code onto the
* blockchain and improve both security and usability. We also educate non-profits,
* schools, and other community members about the application of blockchain
* technology. For further information: majoolr.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 "./BasicMathLib.sol";
import "./TokenLib.sol";
import "./CrowdsaleLib.sol";
library DirectCrowdsaleLib {
using BasicMathLib for uint256;
using CrowdsaleLib for CrowdsaleLib.CrowdsaleStorage;
struct DirectCrowdsaleStorage {
CrowdsaleLib.CrowdsaleStorage base; // base storage from CrowdsaleLib
uint256[] tokenPricePoints; // price points at each price change interval in cents/token.
uint256 changeInterval; // amount of time between changes in the price of the token
uint256 lastPriceChangeTime; // time of the last change in token cost
}
event LogTokensBought(address indexed buyer, uint256 amount);
event LogAddressCapExceeded(address indexed buyer, uint256 amount, string Msg);
event LogErrorMsg(uint256 amount, string Msg);
event LogTokenPriceChange(uint256 amount, string Msg);
/// @dev Called by a crowdsale contract upon creation.
/// @param self Stored crowdsale from crowdsale contract
/// @param _owner Address of crowdsale owner
/// @param _capAmountInCents Total to be raised in cents
/// @param _startTime Timestamp of sale start time
/// @param _endTime Timestamp of sale end time
/// @param _tokenPricePoints Array of each price point during sale cents/token
/// @param _fallbackExchangeRate Exchange rate of cents/ETH
/// @param _changeInterval The number of seconds between each step
/// @param _percentBurn Percentage of extra tokens to burn
/// @param _token Token being sold
function init(DirectCrowdsaleStorage storage self,
address _owner,
uint256 _capAmountInCents,
uint256 _startTime,
uint256 _endTime,
uint256[] _tokenPricePoints,
uint256 _fallbackExchangeRate,
uint256 _changeInterval,
uint8 _percentBurn,
CrowdsaleToken _token)
{
self.base.init(_owner,
_tokenPricePoints[0],
_fallbackExchangeRate,
_capAmountInCents,
_startTime,
_endTime,
_percentBurn,
_token);
require(_tokenPricePoints.length > 0);
// if there is no increase or decrease in price, the time interval should also be zero
if (_tokenPricePoints.length == 1) {
require(_changeInterval == 0);
}
self.tokenPricePoints = _tokenPricePoints;
self.changeInterval = _changeInterval;
self.lastPriceChangeTime = _startTime;
}
/// @dev Called when an address wants to purchase tokens
/// @param self Stored crowdsale from crowdsale contract
/// @param _amount amound of wei that the buyer is sending
/// @return true on succesful purchase
function receivePurchase(DirectCrowdsaleStorage storage self, uint256 _amount) returns (bool) {
require(msg.sender != self.base.owner);
require(self.base.validPurchase());
require((self.base.ownerBalance + _amount) <= self.base.capAmount);
// if the token price increase interval has passed, update the current day and change the token price
if ((self.changeInterval > 0) && (now >= (self.lastPriceChangeTime + self.changeInterval))) {
self.lastPriceChangeTime = self.lastPriceChangeTime + self.changeInterval;
uint256 index = (now-self.base.startTime)/self.changeInterval;
//prevents going out of bounds on the tokenPricePoints array
if (self.tokenPricePoints.length <= index)
index = self.tokenPricePoints.length - 1;
self.base.changeTokenPrice(self.tokenPricePoints[index]);
LogTokenPriceChange(self.base.tokensPerEth,"Token Price has changed!");
}
uint256 numTokens; //number of tokens that will be purchased
bool err;
uint256 newBalance; //the new balance of the owner of the crowdsale
uint256 weiTokens; //temp calc holder
uint256 zeros; //for calculating token
uint256 leftoverWei; //wei change for purchaser
uint256 remainder; //temp calc holder
// Find the number of tokens as a function in wei
(err,weiTokens) = _amount.times(self.base.tokensPerEth);
require(!err);
if(self.base.tokenDecimals <= 18){
zeros = 10**(18-uint256(self.base.tokenDecimals));
numTokens = weiTokens/zeros;
leftoverWei = weiTokens % zeros;
self.base.leftoverWei[msg.sender] += leftoverWei;
} else {
zeros = 10**(uint256(self.base.tokenDecimals)-18);
numTokens = weiTokens*zeros;
}
// can't overflow because it is under the cap
self.base.hasContributed[msg.sender] += _amount - leftoverWei;
require(numTokens <= self.base.token.balanceOf(this));
// calculate the amout of ether in the owners balance
(err,newBalance) = self.base.ownerBalance.plus(_amount-leftoverWei);
require(!err);
self.base.ownerBalance = newBalance; // "deposit" the amount
// can't overflow because it will be under the cap
self.base.withdrawTokensMap[msg.sender] += numTokens;
//subtract tokens from owner's share
(err,remainder) = self.base.withdrawTokensMap[self.base.owner].minus(numTokens);
self.base.withdrawTokensMap[self.base.owner] = remainder;
LogTokensBought(msg.sender, numTokens);
return true;
}
/*Functions "inherited" from CrowdsaleLib library*/
function setTokenExchangeRate(DirectCrowdsaleStorage storage self, uint256 _exchangeRate) returns (bool) {
return self.base.setTokenExchangeRate(_exchangeRate);
}
function setTokens(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.setTokens();
}
function withdrawTokens(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawTokens();
}
function withdrawLeftoverWei(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawLeftoverWei();
}
function withdrawOwnerEth(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawOwnerEth();
}
function crowdsaleActive(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.crowdsaleActive();
}
function crowdsaleEnded(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.crowdsaleEnded();
}
function validPurchase(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.validPurchase();
}
}
| Called when an address wants to purchase tokens self Stored crowdsale from crowdsale contract _amount amound of wei that the buyer is sending return true on succesful purchase if the token price increase interval has passed, update the current day and change the token priceprevents going out of bounds on the tokenPricePoints array | function receivePurchase(DirectCrowdsaleStorage storage self, uint256 _amount) returns (bool) {
require(msg.sender != self.base.owner);
require(self.base.validPurchase());
require((self.base.ownerBalance + _amount) <= self.base.capAmount);
if ((self.changeInterval > 0) && (now >= (self.lastPriceChangeTime + self.changeInterval))) {
self.lastPriceChangeTime = self.lastPriceChangeTime + self.changeInterval;
uint256 index = (now-self.base.startTime)/self.changeInterval;
if (self.tokenPricePoints.length <= index)
index = self.tokenPricePoints.length - 1;
self.base.changeTokenPrice(self.tokenPricePoints[index]);
LogTokenPriceChange(self.base.tokensPerEth,"Token Price has changed!");
}
bool err;
require(!err);
if(self.base.tokenDecimals <= 18){
zeros = 10**(18-uint256(self.base.tokenDecimals));
numTokens = weiTokens/zeros;
leftoverWei = weiTokens % zeros;
self.base.leftoverWei[msg.sender] += leftoverWei;
zeros = 10**(uint256(self.base.tokenDecimals)-18);
numTokens = weiTokens*zeros;
}
require(numTokens <= self.base.token.balanceOf(this));
require(!err);
self.base.withdrawTokensMap[self.base.owner] = remainder;
LogTokensBought(msg.sender, numTokens);
return true;
}
| 1,802,735 |
./full_match/80001/0xFF36c08C58f4a931ef7a457c001470d0B8847125/sources/contracts/IPV2.sol | off-chain signing service can then read the pending transaction from thesmart contract using the getPendingTransaction function, sign it, and broadcast it to the blockchain | function getPendingTransaction(address _user, uint256 _transactionId) public view returns (address to, uint256 value, bytes memory data) {
PendingTransaction storage pendingTransaction = _pendingTransactions[_user][_transactionId];
return (pendingTransaction.to, pendingTransaction.value, pendingTransaction.data);
}
| 5,552,028 |
// contracts/vaults/BalleMaster.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../token/BALLEv2.sol";
import "../interfaces/IStrategy.sol";
/**
* @dev Implementation of the Master of BALLE.
* This contract will take care of all reward calculations and distribution of BALLE tokens in vaults.
* The owner of the contract is the Governance Gnosis Safe multisig.
*/
contract BalleMaster is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Info of each vault
struct VaultInfo {
IERC20 depositToken; // Address of deposited token contract.
address strat; // Address of the strategy contract.
uint256 allocPoint; // How many allocation points assigned to this vault. BALLEs to distribute per block.
uint256 lastRewardBlock; // Last block number that BALLEs distribution occurs.
uint256 accBallePerShare; // Accumulated BALLEs per share, times 1e12. See below.
bool rewardsActive; // BALLE rewards active for this vault.
bool paused; // The vault's strategy is paused.
bool retired; // The vault is retired.
}
// Info of each user
struct UserInfo {
uint256 deposit; // User deposit amount.
uint256 shares; // User shares of the vault.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of BALLEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.shares * vault.accBallePerShare) / 1e12 - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a vault. Here's what happens:
// 1. The vault's `accBallePerShare` and `lastRewardBlock` gets updated.
// 2. User receives the pending reward sent to his address.
// 3. User's `shares` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// The BALLE token.
BALLEv2 public immutable balle;
// BALLE tokens created per block: 2283105022831050.
uint256 public immutable ballePerBlock;
// BALLE tokens to distribute: 24000e18.
uint256 public immutable balleTotalRewards;
// The block number when BALLE rewards distribution starts.
// This is set on constructor, because this contract continues distribution from 0x26FBb0FF7589A43C7d4B2Ff9A68A0519c474156c
uint256 public startBlock;
// The block number when BALLE rewards distribution ends.
uint256 public endBlock;
// Total allocation points. Must be the sum of all allocation points in all vaults.
uint256 public totalAllocPoint = 0;
// BALLE to be minted for rewards.
uint256 public balleToMint = 0;
// Operations Gnosis Safe multisig.
address public operations;
// Security Gnosis Safe multisig.
address public security;
// Info of each vault.
VaultInfo[] public vaultInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event ActivateRewards(uint256 indexed vid, uint256 allocPoint);
event ModifyRewards(uint256 indexed vid, uint256 allocPoint);
event DeactivateRewards(uint256 indexed vid);
event EmergencyStratUpgrade(uint256 indexed vid, address indexed strat);
event PauseVault(uint256 indexed vid);
event UnpauseVault(uint256 indexed vid);
event PanicVault(uint256 indexed vid);
event RetireVault(uint256 indexed vid);
event Deposit(address indexed user, uint256 indexed vid, uint256 amount, uint256 rewards);
event Withdraw(address indexed user, uint256 indexed vid, uint256 amount, uint256 rewards);
event EmergencyWithdraw(address indexed user, uint256 indexed vid, uint256 amount);
constructor(
BALLEv2 _balle,
uint256 _ballePerBlock,
uint256 _balleTotalRewards,
uint256 _startBlock
) {
balle = _balle;
ballePerBlock = _ballePerBlock;
balleTotalRewards = _balleTotalRewards;
startBlock = _startBlock;
}
/**
* @dev Function to change the Operations Gnosis Safe multisig.
*/
function setOperations(address _operations) external onlyOwner {
require(_operations != address(0), "zero address");
operations = _operations;
}
/**
* @dev Function to change the Security Gnosis Safe multisig.
*/
function setSecurity(address _security) external onlyOwner {
require(_security != address(0), "zero address");
security = _security;
}
/**
* @dev Modifier to check the caller is the Governance or Operations Gnosis Safe multisig.
*/
modifier onlyOperations() {
require(msg.sender == operations || msg.sender == owner(), "!operations");
_;
}
/**
* @dev Modifier to check the caller is the Governance, Operations or Security Gnosis Safe multisig.
*/
modifier onlySecurity() {
require(msg.sender == operations || msg.sender == owner() || msg.sender == security, "!security");
_;
}
/**
* @dev Modifier to check if the vault exists.
*/
modifier vaultExists(uint256 pid) {
require(pid < vaultInfo.length, "!vault");
_;
}
/**
* @dev View function to get the number of vaults configured.
*/
function vaultLength() external view returns (uint256) {
return vaultInfo.length;
}
/**
* @dev Function to add a new vault configuration.
*/
function addVault(address _depositToken, address _strat) external onlyOperations {
require(_strat != address(0), "!strat");
require(_depositToken == IStrategy(_strat).depositToken(), "!depositToken");
vaultInfo.push(
VaultInfo({
depositToken: IERC20(_depositToken),
strat: _strat,
allocPoint: 0,
lastRewardBlock: 0,
accBallePerShare: 0,
rewardsActive: false,
paused: false,
retired: false
})
);
}
/**
* @dev Function to activate vault rewards.
*/
function activateVaultRewards(uint256 _vid, uint256 _allocPoint) external onlyOperations vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(!vault.rewardsActive, "active");
require(_allocPoint > 0, "!allocpoint");
massUpdateVaults();
if (startBlock == 0) {
// modified to continue distribution from 0x26FBb0FF7589A43C7d4B2Ff9A68A0519c474156c
startBlock = block.number;
}
if (endBlock == 0) {
endBlock = startBlock + (balleTotalRewards / ballePerBlock);
}
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint + _allocPoint;
vault.allocPoint = _allocPoint;
vault.lastRewardBlock = lastRewardBlock;
vault.rewardsActive = true;
vault.accBallePerShare = 0;
emit ActivateRewards(_vid, _allocPoint);
}
/**
* @dev Function to modify vault rewards.
*/
function modifyVaultRewards(uint256 _vid, uint256 _allocPoint) external onlyOperations vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(vault.rewardsActive, "!active");
require(_allocPoint > 0, "!allocpoint");
massUpdateVaults();
totalAllocPoint = totalAllocPoint - vault.allocPoint + _allocPoint;
vault.allocPoint = _allocPoint;
emit ModifyRewards(_vid, _allocPoint);
}
/**
* @dev Function to deactivate vault rewards.
*/
function deactivateVaultRewards(uint256 _vid) public onlyOperations vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(vault.rewardsActive, "!active");
massUpdateVaults();
totalAllocPoint = totalAllocPoint - vault.allocPoint;
vault.allocPoint = 0;
vault.rewardsActive = false;
emit DeactivateRewards(_vid);
}
/**
* @dev Function to pause vault strategy.
*/
function pauseVault(uint256 _vid) external onlySecurity vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(!vault.paused, "!active");
vault.paused = true;
emit PauseVault(_vid);
IStrategy(vault.strat).pause();
}
/**
* @dev Function to unpause vault strategy.
*/
function unpauseVault(uint256 _vid) external onlyOperations vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(vault.paused, "!paused");
vault.paused = false;
emit UnpauseVault(_vid);
IStrategy(vault.strat).unpause();
}
/**
* @dev Function to panic vault strategy.
*/
function panicVault(uint256 _vid) external onlySecurity vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(!vault.paused, "!active");
vault.paused = true;
emit PanicVault(_vid);
IStrategy(vault.strat).panic();
}
/**
* @dev Function to retire vault strategy.
*/
function retireVault(uint256 _vid) external onlyOperations vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
require(!vault.retired, "!active");
// Make sure rewards are deactivated
if (vault.rewardsActive) {
deactivateVaultRewards(_vid);
}
vault.retired = true;
emit RetireVault(_vid);
IStrategy(vault.strat).retire();
}
/**
* @dev View function to calculate the reward multiplier over the given _from to _to block.
*/
function getBlockMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to < startBlock) {
return 0;
}
if (_from > endBlock) {
return 0;
}
if (_from < startBlock) {
_from = startBlock;
}
if (_to > endBlock) {
_to = endBlock;
}
return _to - _from;
}
/**
* @dev View function to see pending BALLE rewards on frontend.
*/
function pendingRewards(uint256 _vid, address _user) external view returns (uint256) {
VaultInfo storage vault = vaultInfo[_vid];
UserInfo storage user = userInfo[_vid][_user];
uint256 accBallePerShare = vault.accBallePerShare;
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
if (vault.rewardsActive && block.number > vault.lastRewardBlock && sharesTotal != 0) {
uint256 multiplier = getBlockMultiplier(vault.lastRewardBlock, block.number);
uint256 balleReward = (multiplier * ballePerBlock * vault.allocPoint) / totalAllocPoint;
accBallePerShare = accBallePerShare + (balleReward * 1e12) / sharesTotal;
}
return (user.shares * accBallePerShare) / 1e12 - user.rewardDebt;
}
/**
* @dev View function to see user's deposited tokens on frontend.
* This is useful to show the earnings: depositTokens() - userDeposit()
*/
function userDeposit(uint256 _vid, address _user) external view returns (uint256) {
return userInfo[_vid][_user].deposit;
}
/**
* @dev View function to see user's deposit tokens on frontend.
*/
function depositTokens(uint256 _vid, address _user) external view returns (uint256) {
VaultInfo storage vault = vaultInfo[_vid];
UserInfo storage user = userInfo[_vid][_user];
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
uint256 depositTotal = IStrategy(vault.strat).depositTotal();
if (sharesTotal == 0) {
return 0;
}
return (user.shares * depositTotal) / sharesTotal;
}
/**
* @dev Function to update reward variables for all vaults. Be careful of gas spending!
*/
function massUpdateVaults() internal {
uint256 length = vaultInfo.length;
for (uint256 vid = 0; vid < length; ++vid) {
updateVault(vid);
}
}
/**
* @dev Function to update reward variables of the given vault to be up-to-date.
*/
function updateVault(uint256 _vid) internal {
VaultInfo storage vault = vaultInfo[_vid];
if (!vault.rewardsActive) {
return;
}
if (block.number <= vault.lastRewardBlock) {
return;
}
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
if (sharesTotal == 0) {
vault.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getBlockMultiplier(vault.lastRewardBlock, block.number);
if (multiplier <= 0) {
return;
}
uint256 balleReward = (multiplier * ballePerBlock * vault.allocPoint) / totalAllocPoint;
balleToMint = balleToMint + balleReward;
vault.accBallePerShare = vault.accBallePerShare + (balleReward * 1e12) / sharesTotal;
vault.lastRewardBlock = block.number;
}
/**
* @dev Function that moves tokens from user -> BalleMaster (BALLE allocation) -> Strat (compounding).
*/
function _deposit(uint256 _vid, uint256 _amount) internal {
updateVault(_vid);
VaultInfo storage vault = vaultInfo[_vid];
UserInfo storage user = userInfo[_vid][msg.sender];
uint256 pending = 0;
if (user.shares > 0) {
pending = (user.shares * vault.accBallePerShare) / 1e12 - user.rewardDebt;
if (pending > 0) {
safeBalleTransfer(msg.sender, pending);
}
}
if (_amount > 0 && !vault.paused && !vault.retired) {
vault.depositToken.safeTransferFrom(msg.sender, address(this), _amount);
vault.depositToken.safeIncreaseAllowance(vault.strat, _amount);
uint256 sharesAdded = IStrategy(vaultInfo[_vid].strat).deposit(msg.sender, _amount);
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
uint256 depositTotal = IStrategy(vault.strat).depositTotal();
user.shares = user.shares + sharesAdded;
user.deposit = (user.shares * depositTotal) / sharesTotal;
}
user.rewardDebt = (user.shares * vault.accBallePerShare) / 1e12;
emit Deposit(msg.sender, _vid, _amount, pending);
}
/**
* @dev Function that deposits user tokens.
*/
function deposit(uint256 _vid, uint256 _amount) public nonReentrant vaultExists(_vid) {
_deposit(_vid, _amount);
}
/**
* @dev Function that deposits all user tokens balance.
*/
function depositAll(uint256 _vid) public nonReentrant {
VaultInfo storage vault = vaultInfo[_vid];
_deposit(_vid, vault.depositToken.balanceOf(msg.sender));
}
/**
* @dev Function that performs the withdrawal.
*/
function _withdraw(uint256 _vid, uint256 _amount) internal {
updateVault(_vid);
VaultInfo storage vault = vaultInfo[_vid];
UserInfo storage user = userInfo[_vid][msg.sender];
uint256 depositTotal = IStrategy(vault.strat).depositTotal();
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
require(sharesTotal > 0, "!sharesTotal");
require(user.shares > 0, "!user.shares");
// Withdraw pending BALLE
uint256 pending = (user.shares * vault.accBallePerShare) / 1e12 - user.rewardDebt;
if (pending > 0) {
safeBalleTransfer(msg.sender, pending);
}
// Withdraw tokens
uint256 amount = (user.shares * depositTotal) / sharesTotal;
if (_amount > amount) {
_amount = amount;
}
if (_amount > 0) {
(uint256 sharesRemoved, uint256 depositRemoved) = IStrategy(vault.strat).withdraw(msg.sender, _amount);
if (sharesRemoved >= user.shares) {
user.shares = 0;
user.deposit = 0;
} else {
user.shares = user.shares - sharesRemoved;
user.deposit = (user.shares * (depositTotal - depositRemoved)) / (sharesTotal - sharesRemoved);
}
uint256 depositBal = IERC20(vault.depositToken).balanceOf(address(this));
if (depositBal < depositRemoved) {
depositRemoved = depositBal;
}
vault.depositToken.safeTransfer(msg.sender, depositRemoved);
}
user.rewardDebt = (user.shares * vault.accBallePerShare) / 1e12;
emit Withdraw(msg.sender, _vid, _amount, pending);
}
/**
* @dev Function that withdraws user tokens.
*/
function withdraw(uint256 _vid, uint256 _amount) public nonReentrant vaultExists(_vid) {
_withdraw(_vid, _amount);
}
/**
* @dev Function that withdraws all user tokens balance.
*/
function withdrawAll(uint256 _vid) public nonReentrant {
_withdraw(_vid, type(uint256).max);
}
/**
* @dev Function that withdraws without caring about rewards. EMERGENCY ONLY.
*/
function emergencyWithdraw(uint256 _vid) public nonReentrant vaultExists(_vid) {
VaultInfo storage vault = vaultInfo[_vid];
UserInfo storage user = userInfo[_vid][msg.sender];
uint256 depositTotal = IStrategy(vault.strat).depositTotal();
uint256 sharesTotal = IStrategy(vault.strat).sharesTotal();
uint256 amount = (user.shares * depositTotal) / sharesTotal;
user.shares = 0;
user.deposit = 0;
user.rewardDebt = 0;
IStrategy(vault.strat).withdraw(msg.sender, amount);
uint256 lpBal = IERC20(vault.depositToken).balanceOf(address(this));
if (lpBal < amount) {
amount = lpBal;
}
vault.depositToken.safeTransfer(msg.sender, amount);
emit EmergencyWithdraw(msg.sender, _vid, amount);
}
/**
* @dev Function for Safe BALLE transfer.
* Will mint BALLE when needed and take care if rounding error causes pool to not have enough BALLE.
*/
function safeBalleTransfer(address _to, uint256 _amount) internal {
uint256 balleBal = balle.balanceOf(address(this));
if (_amount > balleBal) {
if (balleToMint > 0) {
balle.mint(address(this), balleToMint);
balleToMint = 0;
balleBal = balle.balanceOf(address(this));
if (_amount > balleBal) {
balle.transfer(_to, balleBal);
} else {
balle.transfer(_to, _amount);
}
} else {
balle.transfer(_to, balleBal);
}
} else {
balle.transfer(_to, _amount);
}
}
/**
* @dev Function to use from Governance Gnosis Safe multisig only in case tokens get stuck.
* This is to be used if someone, for example, sends tokens to the contract by mistake.
* There is no guarantee governance will vote to return these.
*/
function inCaseTokensGetStuck(
address _token,
uint256 _amount,
address _to
) external onlyOwner {
require(_to != address(0), "zero address");
require(_token != address(balle), "!safe");
IERC20(_token).safeTransfer(_to, _amount);
}
}
| Function to update reward variables for all vaults. Be careful of gas spending!/ | function massUpdateVaults() internal {
uint256 length = vaultInfo.length;
for (uint256 vid = 0; vid < length; ++vid) {
updateVault(vid);
}
}
| 5,392,879 |
./partial_match/5/0x5De88AF8F75A360B357760B6Bd61786A2C48b326/sources/contracts/3hree.sol | Creates `_amount` token to `_to`. Owner is MasterChef Contract. | function mint(address _to, uint256 _amount) public onlyOwner {
require(ERC20.totalSupply() + _amount <= maxSupply(), "ERC20Capped: max supply reached");
_mint(_to, _amount);
}
| 16,886,538 |
./full_match/1/0x333F0C9dC07686d458C6a171DaBA777485BbE4E3/sources/contracts/Wallet.sol | only owner can withdraw tokens token - token address _amount - amount of tokens to withdraw/ | function withdrawToken(IERC20 token, uint256 _amount) external onlyOwner {
if (IERC20(token).balanceOf(address(this)) < _amount) revert InsufficientBalance();
_safeWithdrawToken(msg.sender, token, _amount);
}
| 2,898,545 |
./partial_match/1/0x31577476950ec86E2D6D99dcc756A35AEa14389a/sources/MultiProductEscrow.sol | Only the seller can execute these functions./ | modifier onlySeller(string calldata transactionId) {
TransactionInfo memory transactionInfo = transactions[transactionId];
require(transactionInfo.created, "Invalid transaction.");
require(!transactionInfo.completed, "Transaction already completed.");
require(
transactionInfo.sellerAddress == msg.sender,
"Only the seller can call this function."
);
_;
}
| 16,070,563 |
./full_match/421611/0x481148ed881807B574548B759141A0F515060d3f/sources/_aave/core-v3/contracts/protocol/libraries/logic/ReserveLogic.sol | Updates the reserve indexes and the timestamp of the update reserve The reserve reserve to be updated reserveCache The cache layer holding the cached protocol data/only cumulating if there is any income being producedas the liquidity rate might come only from stable rate loans, we need to ensurethat there is actual variable debt before accumulating | function _updateIndexes(
DataTypes.ReserveData storage reserve,
DataTypes.ReserveCache memory reserveCache
) internal {
reserveCache.nextLiquidityIndex = reserveCache.currLiquidityIndex;
reserveCache.nextVariableBorrowIndex = reserveCache.currVariableBorrowIndex;
if (reserveCache.currLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(
reserveCache.currLiquidityRate,
reserveCache.reserveLastUpdateTimestamp
);
reserveCache.nextLiquidityIndex = cumulatedLiquidityInterest.rayMul(
reserveCache.currLiquidityIndex
);
reserve.liquidityIndex = Helpers.castUint128(reserveCache.nextLiquidityIndex);
if (reserveCache.currScaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(
reserveCache.currVariableBorrowRate,
reserveCache.reserveLastUpdateTimestamp
);
reserveCache.nextVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(
reserveCache.currVariableBorrowIndex
);
reserve.variableBorrowIndex = Helpers.castUint128(reserveCache.nextVariableBorrowIndex);
}
}
}
| 13,220,321 |
// @author Unstoppable Domains, Inc.
// @date June 16th, 2021
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import './BaseForwarder.sol';
abstract contract EIP712UpgradeableGap {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
uint256[50] private __gap;
/* solhint-enable var-name-mixedcase */
}
/**
* @dev https://eips.ethereum.org/EIPS/eip-2771[EIP 2771] is a standard for native meta transactions.
*
* A base contract to be inherited by any contract that want to forward transactions.
*/
abstract contract UNSRegistryForwarder is Initializable, EIP712UpgradeableGap, BaseForwarder {
mapping(uint256 => uint256) private _nonces;
// solhint-disable-next-line func-name-mixedcase
function __UNSRegistryForwarder_init() internal initializer {
__UNSRegistryForwarder_init_unchained();
}
// solhint-disable-next-line func-name-mixedcase
function __UNSRegistryForwarder_init_unchained() internal initializer {}
/*
* 0x23b872dd == bytes4(keccak256('transferFrom(address,address,uint256)'))
*/
function transferFromFor(
address from,
address to,
uint256 tokenId,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0x23b872dd, from, to, tokenId), tokenId, signature, gas);
}
/*
* 0x42842e0e == bytes4(keccak256('safeTransferFrom(address,address,uint256)'))
*/
function safeTransferFromFor(
address from,
address to,
uint256 tokenId,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0x42842e0e, from, to, tokenId), tokenId, signature, gas);
}
/*
* 0xb88d4fde == bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
function safeTransferFromFor(
address from,
address to,
uint256 tokenId,
bytes calldata data,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0xb88d4fde, from, to, tokenId, data), tokenId, signature, gas);
}
/*
* 0x42966c68 == bytes4(keccak256('burn(uint256)'))
*/
function burnFor(uint256 tokenId, bytes calldata signature) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0x42966c68, tokenId), tokenId, signature, gas);
}
/*
* 0x310bd74b == bytes4(keccak256('reset(uint256)'))
*/
function resetFor(uint256 tokenId, bytes calldata signature) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0x310bd74b, tokenId), tokenId, signature, gas);
}
/*
* 0x47c81699 == bytes4(keccak256('set(string,string,uint256)'))
*/
function setFor(
string calldata key,
string calldata value,
uint256 tokenId,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0x47c81699, key, value, tokenId), tokenId, signature, gas);
}
/*
* 0xce92b33e == bytes4(keccak256('setMany(string[],string[],uint256)'))
*/
function setManyFor(
string[] calldata keys,
string[] calldata values,
uint256 tokenId,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0xce92b33e, keys, values, tokenId), tokenId, signature, gas);
}
/*
* 0xec129eea == bytes4(keccak256('reconfigure(string[],string[],uint256)'))
*/
function reconfigureFor(
string[] calldata keys,
string[] calldata values,
uint256 tokenId,
bytes calldata signature
) public {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0xec129eea, keys, values, tokenId), tokenId, signature, gas);
}
function nonceOf(uint256 tokenId) public view override returns (uint256) {
return _nonces[tokenId];
}
function verify(ForwardRequest calldata req, bytes calldata signature) public view override returns (bool) {
return _verify(req, address(this), signature);
}
function execute(ForwardRequest calldata req, bytes calldata signature) public override returns (bytes memory) {
uint256 gas = gasleft();
require(verify(req, signature), 'UNSRegistryForwarder: SIGNATURE_INVALID');
return _execute(req.from, address(this), req.tokenId, gas, req.data, signature);
}
function _invalidateNonce(uint256 tokenId) internal override {
_nonces[tokenId] = _nonces[tokenId] + 1;
}
function _executeFor(
bytes memory data,
uint256 tokenId,
bytes memory signature,
uint256 gas
) private returns (bytes memory) {
address from = _recover(keccak256(data), address(this), _nonces[tokenId], signature);
return _execute(from, address(this), tokenId, gas, data, signature);
}
uint256[50] private __gap;
}
| 0xb88d4fde == bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))/ | function safeTransferFromFor(
address from,
address to,
uint256 tokenId,
bytes calldata data,
bytes calldata signature
) external {
uint256 gas = gasleft();
_executeFor(abi.encodeWithSelector(0xb88d4fde, from, to, tokenId, data), tokenId, signature, gas);
}
| 14,053,458 |
./partial_match/7700/0x156ecfbdd58b9012192b5B36B1164FfA60e605A0/sources/contracts/Flow.sol | Initial mint: total 400m we will handle the creation of the veNFTs ourselves and not use minter 4M for "Genesis" pools 30M for liquid team allocation (40M excl init veNFT) 48M for future partners | function initialMint(address _recipient) external {
require(msg.sender == minter && !initialMinted);
initialMinted = true;
_mint(_recipient, 200 * 1e6 * 1e18);
}
| 3,507,976 |
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "./IFoxGameNFTTraits.sol";
import "./IFoxGameCarrot.sol";
import "./IFoxGameCrown.sol";
import "./IFoxGameNFT.sol";
import "./IFoxGame.sol";
contract FoxGameNFTGen1_v1_1 is IFoxGameNFT, ERC721EnumerableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using ECDSAUpgradeable for bytes32; // signature verification helpers
// Presale status
bool public saleActive;
// Mumber of players minted
uint16 public minted;
// External contracts
IFoxGameCarrot private foxCarrot;
IFoxGameNFTTraits private foxTraits;
IFoxGame private foxGame;
// Maximum players in the game
uint16 public constant MAX_TOKENS = 50000;
// Number of GEN 0 tokens
uint16 public constant MAX_GEN0_TOKENS = 10000;
// Rarity trait probabilities
uint8[][29] private rarities;
uint8[][29] private aliases;
// Mapping of token ID to player traits
mapping(uint16 => Traits) private tokenTraits;
// Store previous trait combinations to prevent duplicates
mapping(uint256 => bool) private knownCombinations;
// Store origin seeds for each token
mapping(uint32 => uint256) private tokenSeeds;
// Events
event SaleActive(bool active);
event Mint(string kind, address owner, uint16 tokenId);
event MintStolen(address thief, address victim, string kind, uint16 tokenId);
// Mapping of traits to metadata display names
string[3] private _types;
// Store the latest block number to setup future calls requiring randomness
// Address => Coin => Block Number
mapping(address => mapping(IFoxGameNFT.Coin => uint32)) private _lastMintBlock;
// Crown utility token
IFoxGameCrown private foxCrown;
// Event to handle mint failures
event MintFailure(address account);
// Init contract upgradability (only called once)
function initialize(address carrot, address game, address traits) public initializer {
__ERC721_init("FoxGame", "FOX");
__ERC721Enumerable_init();
__Ownable_init();
__ReentrancyGuard_init();
foxCarrot = IFoxGameCarrot(carrot);
foxGame = IFoxGame(game);
foxTraits = IFoxGameNFTTraits(traits);
// Gen 1 starting token ID
minted = MAX_GEN0_TOKENS;
// Define token type names
_types = [ "Rabbit", "Fox", "Hunter" ];
// Precomputed rarity probabilities on chain.
// (via walker's alias algorithm)
// RABBIT
// Fur
rarities[0] = [ 153, 153, 255, 102, 77, 230 ];
aliases[0] = [ 2, 2, 0, 2, 3, 3 ];
// Paws
rarities[1] = [ 61, 184, 122, 122, 61, 255, 204, 122, 224, 255, 214, 184, 235, 61, 184, 184, 184, 122, 122, 184, 153, 245, 143, 224 ];
aliases[1] = [ 6, 8, 8, 9, 10, 0, 5, 15, 6, 8, 9, 15, 10, 20, 20, 12, 21, 22, 23, 23, 15, 20, 21, 22 ];
// Mouth
rarities[2] = [ 191, 77, 191, 255, 38, 115, 204, 153, 191, 38, 64, 115, 77, 115, 128 ];
aliases[2] = [ 3, 3, 3, 0, 7, 7, 3, 6, 7, 10, 8, 13, 14, 10, 13 ];
// Nose
rarities[3] = [ 255, 242, 153, 204, 115, 230, 230, 115, 115 ];
aliases[3] = [ 0, 0, 1, 2, 0, 0, 0, 2, 3 ];
// Eyes
rarities[4] = [ 77, 255, 128, 77, 153, 153, 153, 77, 153, 230, 77, 77, 77, 204, 179, 230, 77, 179, 128, 179, 153, 230, 77, 77, 102, 77, 153, 153, 204, 77 ];
aliases[4] = [ 3, 0, 1, 2, 13, 13, 13, 13, 14, 14, 18, 19, 20, 3, 13, 20, 24, 14, 17, 18, 19, 20, 25, 25, 21, 24, 25, 26, 26, 28 ];
// Ears
rarities[5] = [ 41, 61, 102, 204, 255, 102, 204, 204 ];
aliases[5] = [ 5, 5, 5, 5, 0, 4, 5, 5 ];
// Head
rarities[6] = [ 87, 255, 130, 245, 173, 173, 191, 87, 176, 128, 217, 43, 173, 217, 92, 217, 43 ];
aliases[6] = [ 1, 0, 3, 1, 6, 6, 3, 9, 6, 8, 9, 9, 9, 9, 9, 9, 14 ];
// FOX
// Tail
rarities[7] = [ 255, 153, 204, 102 ];
aliases[7] = [ 0, 0, 0, 1 ];
// Fur
rarities[8] = [ 255, 204, 153, 153 ];
aliases[8] = [ 0, 0, 1, 1 ];
// Feet
rarities[9] = [ 255, 255, 229, 204, 229, 204, 179, 255, 255, 128 ];
aliases[9] = [ 0, 0, 1, 2, 3, 2, 3, 0, 0, 4 ];
// Neck
rarities[10] = [ 255, 204, 204, 204, 127, 102, 51, 255, 255, 26 ];
aliases[10] = [ 0, 0, 1, 0, 2, 0, 1, 0, 0, 4 ];
// Mouth
rarities[11] = [ 255, 102, 255, 255, 204, 153, 102, 255, 51, 51, 255, 204, 255, 204, 153, 204, 153, 51, 255, 51 ];
aliases[11] = [ 0, 2, 0, 2, 3, 2, 4, 6, 6, 6, 0, 7, 11, 12, 13, 7, 11, 13, 0, 14 ];
// Eyes
rarities[12] = [ 56, 255, 179, 153, 158, 112, 133, 112, 112, 56, 250, 224, 199, 122, 240, 214, 189, 112, 112, 163, 112, 138 ];
aliases[12] = [ 1, 0, 1, 2, 3, 1, 4, 3, 6, 12, 6, 10, 11, 12, 13, 14, 15, 12, 13, 16, 21, 19 ];
// Cunning Score
rarities[13] = [ 255, 153, 204, 102 ];
aliases[13] = [ 0, 0, 0, 1 ];
// HUNTER
// Clothes
rarities[14] = [ 128, 255, 128, 64, 255 ];
aliases[14] = [ 2, 0, 1, 2, 0 ];
// Weapon
rarities[15] = [ 255, 153, 204, 102 ];
aliases[15] = [ 0, 0, 0, 1 ];
// Neck
rarities[16] = [ 102, 255, 26, 153, 255 ];
aliases[16] = [ 1, 0, 3, 1, 0 ];
// Mouth
rarities[17] = [ 255, 229, 179, 179, 89, 179, 217 ];
aliases[17] = [ 0, 0, 0, 6, 6, 6, 1 ];
// Eyes
rarities[18] = [ 191, 255, 38, 77, 191, 77, 217, 38, 153, 191, 77, 191, 204, 77, 77 ];
aliases[18] = [ 1, 0, 4, 4, 1, 4, 5, 5, 6, 5, 5, 6, 8, 8, 12 ];
// Hat
rarities[19] = [ 191, 38, 89, 255, 191 ];
aliases[19] = [ 3, 4, 4, 0, 3 ];
// Marksman Score
rarities[20] = [ 255, 153, 204, 102 ];
aliases[20] = [ 0, 0, 0, 1 ];
}
/**
* Update the utility token contract address.
*/
function setCrownContract(address _address) external onlyOwner {
foxCrown = IFoxGameCrown(_address);
}
/**
* Helper method to fetch rotating entropy used to generate random seeds off-chain.
*/
function getEntropy(address recipient, IFoxGameNFT.Coin token) external view returns (uint256) {
require(tx.origin == msg.sender, "eos only");
// Last mint block (defaults to zero the first time)
return _lastMintBlock[recipient][token];
}
/**
* Upload rarity propbabilties. Only used in emergencies.
* @param traitTypeId trait name id (0 corresponds to "fur")
* @param _rarities walker rarity probailities
* @param _aliases walker aliases index
*/
function uploadTraits(uint8 traitTypeId, uint8[] calldata _rarities, uint8[] calldata _aliases) external onlyOwner {
rarities[traitTypeId] = _rarities;
aliases[traitTypeId] = _aliases;
}
/**
* Enable Sale.
*/
function toggleSale() external onlyOwner {
saleActive = !saleActive;
emit SaleActive(saleActive);
}
/**
* Update the utility token contract address.
*/
function setCarrotContract(address _address) external onlyOwner {
foxCarrot = IFoxGameCarrot(_address);
}
/**
* Update the staking contract address.
*/
function setGameContract(address _address) external onlyOwner {
foxGame = IFoxGame(_address);
}
/**
* Update the ERC-721 trait contract address.
*/
function setTraitsContract(address _address) external onlyOwner {
foxTraits = IFoxGameNFTTraits(_address);
}
/**
* Expose traits to trait contract.
*/
function getTraits(uint16 tokenId) external view override returns (Traits memory) {
return tokenTraits[tokenId];
}
/**
* Expose maximum GEN 0 tokens.
*/
function getMaxGEN0Players() external pure override returns (uint16) {
return MAX_GEN0_TOKENS;
}
/**
* Mint your players.
* @param amount number of tokens to mint
* @param stake mint directly to staking
* @param token token to mint with (0 = CARRROT, 1 = CROWN)
* @param blocknum block number used to generate randomness
* @param originSeed account seed
* @param sig signature
*/
function mint(uint32 amount, bool stake, IFoxGameNFT.Coin token, uint32 blocknum, uint256 originSeed, bytes calldata sig) external payable nonReentrant {
require(blocknum == _lastMintBlock[msg.sender][token], "seed block did not match");
require(tx.origin == msg.sender, "eos only");
require(saleActive, "minting is not active");
require(minted + amount <= MAX_TOKENS, "minted out");
require(amount > 0 && amount <= 20, "invalid mint amount");
require(msg.value == 0, "only carrots required");
require(token == IFoxGameNFT.Coin.CARROT || token == IFoxGameNFT.Coin.CROWN, "unknown token");
require(foxGame.isValidMintSignature(msg.sender, uint8(token), blocknum, originSeed, sig), "invalid signature");
// CARROT mints are only allowed when holding a Barrel
bool ownsBarrel = foxGame.ownsBarrel(msg.sender);
require(token != IFoxGameNFT.Coin.CARROT || ownsBarrel, "CARROT minting requires a barrel");
// Update block for next mint
_lastMintBlock[msg.sender][token] = uint32(block.number);
// Determine if user is facing greater risk of losing mint
bool elevatedRisk = foxGame.getCorruptionEnabled() && !ownsBarrel;
// Mint tokens
Kind kind;
uint16[] memory tokenIdsToStake = stake ? new uint16[](amount) : new uint16[](0);
uint256 mintCost;
uint256 seed;
string memory kindLabel;
for (uint32 i; i < amount; i++) {
minted++;
seed = _reseedWithIndex(originSeed, minted + i);
mintCost += getMintCost(token, minted);
// Handle failure to mint
if (token == IFoxGameNFT.Coin.CARROT && (seed >> 224) % 10 != 0) {
minted--; // dial back token id
emit MintFailure(msg.sender);
continue;
}
kind = _generateAndStoreTraits(minted, seed, 0).kind;
kindLabel = _types[uint8(kind)];
address recipient = _selectRecipient(seed, elevatedRisk);
if (recipient != msg.sender) { // Stolen
_safeMint(recipient, minted);
emit MintStolen(recipient, msg.sender, kindLabel, minted);
} else {
if (stake) { // Staked
tokenIdsToStake[i] = minted;
_safeMint(address(foxGame), minted);
} else { // Mint
_safeMint(msg.sender, minted);
}
emit Mint(kindLabel, msg.sender, minted);
}
}
// Burn
if (token == IFoxGameNFT.Coin.CARROT) {
foxCarrot.burn(msg.sender, mintCost);
} else {
foxCrown.burn(msg.sender, mintCost);
}
// Stake
if (stake) {
foxGame.stakeTokens(msg.sender, tokenIdsToStake);
}
}
/**
* Calculate the foxCarrot cost:
* - the first 20% are 20000 $CROWN / 120000 $CARROT
* - the next 40% are 40000 $CROWN / 140000 $CARROT
* - the final 20% are 80000 $CROWN / 180000 $CARROT
* @param token utility token to pay for mint
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function getMintCost(IFoxGameNFT.Coin token, uint16 tokenId) public pure returns (uint256) {
if (token == IFoxGameNFT.Coin.CARROT) {
if (tokenId <= 20000) return 120000 ether;
if (tokenId <= 40000) return 140000 ether;
return 180000 ether;
} else { // CROWN
if (tokenId <= 20000) return 20000 ether;
if (tokenId <= 40000) return 40000 ether;
return 80000 ether;
}
}
/**
* Generate and store player traits. Recursively called to ensure uniqueness.
* Give users 3 attempts, bit shifting the seed each time (uses 5 bytes of entropy before failing)
* @param tokenId id of the token to generate traits
* @param seed random 256 bit seed to derive traits
* @return t player trait struct
*/
function _generateAndStoreTraits(uint16 tokenId, uint256 seed, uint8 attempt) internal returns (Traits memory t) {
require(attempt < 6, "unable to generate unique traits");
t = _selectTraits(seed);
if (!knownCombinations[_structToHash(t)]) {
tokenTraits[tokenId] = t;
knownCombinations[_structToHash(t)] = true;
return t;
}
return _generateAndStoreTraits(tokenId, seed >> attempt, attempt + 1);
}
/**
* uses A.J. Walker's Alias algorithm for O(1) rarity table lookup
* ensuring O(1) instead of O(n) reduces mint cost by more than 50%
* probability & alias tables are generated off-chain beforehand
* @param seed portion of the 256 bit seed to remove trait correlation
* @param traitType the trait type to select a trait for
* @return the ID of the randomly selected trait
*/
function _selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) {
uint8 trait = uint8(seed) % uint8(rarities[traitType].length);
if (seed >> 8 < rarities[traitType][trait]) return trait;
return aliases[traitType][trait];
}
/**
* the first 20% (ETH purchases) go to the minter
* the remaining 80% have a 10% chance to be given to a random staked fox
* @param seed a random value to select a recipient from
* @param elevatedRisk true if the user is at higher risk of losing their mint
* @return the address of the recipient (either the minter or the fox thief's owner)
*/
function _selectRecipient(uint256 seed, bool elevatedRisk) internal view returns (address) {
if (((seed >> 245) % (elevatedRisk ? 4 : 10)) != 0) {
return msg.sender; // top 10 bits haven't been used
}
// 144 bits reserved for trait selection
address thief = foxGame.randomFoxOwner(seed >> 144);
if (thief == address(0x0)) {
return msg.sender;
}
return thief;
}
/**
* selects the species and all of its traits based on the seed value
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t struct of randomly selected traits
*/
function _selectTraits(uint256 seed) internal view returns (Traits memory t) {
uint mod = (seed & 0xFFFF) % 50;
t.kind = Kind(mod == 0 ? 2 : mod < 5 ? 1 : 0);
// Use 128 bytes of seed entropy to define traits.
uint8 offset = uint8(t.kind) * 7; // RABBIT FOX HUNTER
seed >>= 16; t.traits[0] = _selectTrait(uint16(seed & 0xFFFF), 0 + offset); // Fur Tail Clothes
seed >>= 16; t.traits[1] = _selectTrait(uint16(seed & 0xFFFF), 1 + offset); // Head Fur Weapon
seed >>= 16; t.traits[2] = _selectTrait(uint16(seed & 0xFFFF), 2 + offset); // Ears Eyes Neck
seed >>= 16; t.traits[3] = _selectTrait(uint16(seed & 0xFFFF), 3 + offset); // Eyes Mouth Mouth
seed >>= 16; t.traits[4] = _selectTrait(uint16(seed & 0xFFFF), 4 + offset); // Nose Neck Eyes
seed >>= 16; t.traits[5] = _selectTrait(uint16(seed & 0xFFFF), 5 + offset); // Mouth Feet Hat
seed >>= 16; t.traits[6] = _selectTrait(uint16(seed & 0xFFFF), 6 + offset); // Paws Cunning Marksman
if (t.kind == IFoxGameNFT.Kind.FOX) {
t.advantage = t.traits[6] = t.traits[0];
} else if (t.kind == IFoxGameNFT.Kind.HUNTER) {
t.advantage = t.traits[6] = t.traits[1];
}
}
/**
* converts a struct to a 256 bit hash to check for uniqueness
* @param t the struct to pack into a hash
* @return the 256 bit hash of the struct
*/
function _structToHash(Traits memory t) internal pure returns (uint256) {
return uint256(bytes32(
abi.encodePacked(
t.kind,
t.advantage,
t.traits[0],
t.traits[1],
t.traits[2],
t.traits[3],
t.traits[4],
t.traits[5],
t.traits[6]
)
));
}
/**
* Reseeds entropy with mint amount offset.
* @param seed random seed
* @param offset additional entropy during mint
* @return rotated seed
*/
function _reseedWithIndex(uint256 seed, uint32 offset) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(seed, offset)));
}
/**
* Allow private sales.
*/
function mintToAddress(uint256 amount, address recipient, uint256 originSeed) external onlyOwner {
require(minted + amount <= MAX_TOKENS, "minted out");
require(amount > 0, "invalid mint amount");
Kind kind;
uint256 seed;
for (uint32 i; i < amount; i++) {
minted++;
seed = _reseedWithIndex(originSeed, minted);
kind = _generateAndStoreTraits(minted, seed, 0).kind;
_safeMint(recipient, minted);
emit Mint(kind == Kind.RABBIT ? "RABBIT" : kind == Kind.FOX ? "FOX" : "HUNTER", recipient, minted);
}
}
/**
* Allows owner to withdraw funds from minting.
*/
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/**
* Override transfer to avoid the approval step during staking.
*/
function transferFrom(address from, address to, uint256 tokenId) public override(IFoxGameNFT, ERC721Upgradeable) {
if (msg.sender != address(foxGame)) {
require(_isApprovedOrOwner(msg.sender, tokenId), "transfer not owner nor approved");
}
_transfer(from, to, tokenId);
}
/**
* Override NFT token uri. Calls into traits contract.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "nonexistent token");
return foxTraits.tokenURI(uint16(tokenId));
}
/**
* Ennumerate tokens by owner.
*/
function tokensOf(address owner) external view returns (uint16[] memory) {
uint32 tokenCount = uint32(balanceOf(owner));
uint16[] memory tokensId = new uint16[](tokenCount);
for (uint32 i; i < tokenCount; i++){
tokensId[i] = uint16(tokenOfOwnerByIndex(owner, i));
}
return tokensId;
}
/**
* Overridden to resolve multiple inherited interfaces.
*/
function ownerOf(uint256 tokenId) public view override(IFoxGameNFT, ERC721Upgradeable) returns (address) {
return super.ownerOf(tokenId);
}
/**
* Overridden to resolve multiple inherited interfaces.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override(IFoxGameNFT, ERC721Upgradeable) {
super.safeTransferFrom(from, to, tokenId, _data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.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].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 ECDSAUpgradeable {
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.10;
interface IFoxGameNFTTraits {
function tokenURI(uint16 tokenId) external view returns (string memory);
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameCarrot {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameCrown {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameNFT {
enum Kind { RABBIT, FOX, HUNTER }
enum Coin { CARROT, CROWN }
struct Traits { Kind kind; uint8 advantage; uint8[7] traits; }
function getMaxGEN0Players() external pure returns (uint16);
function getTraits(uint16) external view returns (Traits memory);
function ownerOf(uint256) external view returns (address owner);
function transferFrom(address, address, uint256) external;
function safeTransferFrom(address, address, uint256, bytes memory) external;
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGame {
function stakeTokens(address, uint16[] calldata) external;
function randomFoxOwner(uint256) external view returns (address);
function isValidMintSignature(address, uint8, uint32, uint256, bytes memory) external view returns (bool);
function ownsBarrel(address) external view returns (bool);
function getCorruptionEnabled() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | the first 20% (ETH purchases) go to the minter the remaining 80% have a 10% chance to be given to a random staked fox seed a random value to select a recipient from elevatedRisk true if the user is at higher risk of losing their mint return the address of the recipient (either the minter or the fox thief's owner)/ | function _selectRecipient(uint256 seed, bool elevatedRisk) internal view returns (address) {
if (((seed >> 245) % (elevatedRisk ? 4 : 10)) != 0) {
}
address thief = foxGame.randomFoxOwner(seed >> 144);
if (thief == address(0x0)) {
return msg.sender;
}
return thief;
}
| 14,591,681 |
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity 0.8.3;
import "./ABDKMath64x64.sol";
library BlackScholes {
/**
* @dev Function to get the option price using the Black-Sholes method.
* @param isCallOption True if the option type is CALL, false for PUT.
* @param strikePrice The strike price value with `pricePrecision`.
* @param currentPrice The current underlying price value with `pricePrecision`.
* @param pricePrecision The price precision, for example for an asset with 6 decimals it will be 1000000.
* @param secondsToExpire Seconds to the option expiry.
* @param annualVolatilityPercentage The annual volatility with `percentageDataPrecision`.
* @param annualInterestRate The annual interest rate with `percentageDataPrecision`.
* @param annualDividendYield The annual dividen yield with `percentageDataPrecision`.
* @param percentageDataPrecision The percentage precision,
* for example it must be 100000 wheter 100000=100%, 25000=25%, 250750=250.75% etc.
* @return The calculated option price with `pricePrecision`.
*/
function getOptionPrice(
bool isCallOption,
uint256 strikePrice,
uint256 currentPrice,
uint256 pricePrecision,
uint256 secondsToExpire,
uint256 annualVolatilityPercentage,
uint256 annualInterestRate,
uint256 annualDividendYield,
uint256 percentageDataPrecision
) internal pure returns (uint256) {
return
ABDKMath64x64.mulu(
_blackScholesCalculation(
isCallOption,
ABDKMath64x64.divu(strikePrice, pricePrecision),
ABDKMath64x64.divu(currentPrice, pricePrecision),
ABDKMath64x64.divu(annualVolatilityPercentage, percentageDataPrecision),
ABDKMath64x64.divu(annualInterestRate, percentageDataPrecision),
ABDKMath64x64.divu(annualDividendYield, percentageDataPrecision),
ABDKMath64x64.divu(secondsToExpire, 0x1e13380)
),
pricePrecision
);
}
/**
* @dev Private function to handle with the Black-Sholes calculation.
* @param isCallOption True if the option type is CALL, false for PUT.
* @param strikePrice The strike price normalized with `ABDKMath64x64` library.
* @param currentPrice The current underlying price normalized with `ABDKMath64x64` library.
* @param volatility The annual volatility normalized with `ABDKMath64x64` library.
* @param interestRate The annual interest rate normalized with `ABDKMath64x64` library.
* @param dividendYield The annual dividen yield normalized with `ABDKMath64x64` library.
* @param expiration The expiration annual equivalent percentage normalized with `ABDKMath64x64` library.
* @return The calculated option price normalized with `ABDKMath64x64` library.
*/
function _blackScholesCalculation(
bool isCallOption,
int128 strikePrice,
int128 currentPrice,
int128 volatility,
int128 interestRate,
int128 dividendYield,
int128 expiration
) private pure returns (int128) {
int128 dCalculationAux = ABDKMath64x64.mul(volatility, ABDKMath64x64.sqrt(expiration));
int128 d1 =
_d1Calculation(
strikePrice,
currentPrice,
expiration,
volatility,
interestRate,
dividendYield,
dCalculationAux
);
int128 d2 = ABDKMath64x64.sub(d1, dCalculationAux);
return
_priceCalculation(isCallOption, strikePrice, currentPrice, interestRate, dividendYield, expiration, d1, d2);
}
/**
* @dev Private function to calculate the option price with the Black-Sholes method.
* @param isCallOption True if the option type is CALL, false for PUT.
* @param strikePrice The strike price normalized with `ABDKMath64x64` library.
* @param currentPrice The current underlying price normalized with `ABDKMath64x64` library.
* @param interestRate The annual interest rate normalized with `ABDKMath64x64` library.
* @param dividendYield The annual dividen yield normalized with `ABDKMath64x64` library.
* @param expiration The expiration annual equivalent percentage normalized with `ABDKMath64x64` library.
* @param d1 The D1 argument on Black-Sholes method normalized with `ABDKMath64x64` library.
* @param d2 The D2 argument on Black-Sholes method normalized with `ABDKMath64x64` library.
* @return The calculated option price normalized with `ABDKMath64x64` library.
*/
function _priceCalculation(
bool isCallOption,
int128 strikePrice,
int128 currentPrice,
int128 interestRate,
int128 dividendYield,
int128 expiration,
int128 d1,
int128 d2
) private pure returns (int128) {
int128 dividendYieldFactor = _getRateFactor(dividendYield, expiration);
int128 interestRateFactor = _getRateFactor(interestRate, expiration);
if (isCallOption) {
return
ABDKMath64x64.sub(
ABDKMath64x64.mul(
dividendYieldFactor,
ABDKMath64x64.mul(currentPrice, _normalCummulativeDistribution(d1))
),
ABDKMath64x64.mul(
interestRateFactor,
ABDKMath64x64.mul(strikePrice, _normalCummulativeDistribution(d2))
)
);
} else {
return
ABDKMath64x64.sub(
ABDKMath64x64.mul(
interestRateFactor,
ABDKMath64x64.mul(strikePrice, _normalCummulativeDistribution(ABDKMath64x64.neg(d2)))
),
ABDKMath64x64.mul(
dividendYieldFactor,
ABDKMath64x64.mul(currentPrice, _normalCummulativeDistribution(ABDKMath64x64.neg(d1)))
)
);
}
}
/**
* @dev Private function to calculate the normal cummulative distribution.
* @param x The value normalized with `ABDKMath64x64` library to be calculated.
* @return The normal cummulative distribution normalized with `ABDKMath64x64` library.
*/
function _normalCummulativeDistribution(int128 x) private pure returns (int128) {
int128 z = ABDKMath64x64.div(x, 0x16a09e667f3bcc908);
int128 t =
ABDKMath64x64.div(
0x10000000000000000,
ABDKMath64x64.add(0x10000000000000000, ABDKMath64x64.mul(0x53dd02a4f5ee2e46, ABDKMath64x64.abs(z)))
);
int128 erf = _getErf(z, t);
int128 nerf = erf;
if (z < 0) {
nerf = ABDKMath64x64.neg(erf);
}
return ABDKMath64x64.mul(0x8000000000000000, ABDKMath64x64.add(0x10000000000000000, nerf));
}
/**
* @dev Private function to calculate the ERF.
* @param z The `z` argument normalized with `ABDKMath64x64` library.
* @param t The `t` argument normalized with `ABDKMath64x64` library.
* @return The ERF normalized with `ABDKMath64x64` library.
*/
function _getErf(int128 z, int128 t) private pure returns (int128) {
int128 f =
ABDKMath64x64.mul(
t,
ABDKMath64x64.add(
0x16be1c55bae156b65,
ABDKMath64x64.mul(
t,
ABDKMath64x64.add(-0x17401c57014c38f14, ABDKMath64x64.mul(t, 0x10fb844255a12d72e))
)
)
);
int128 f2 =
ABDKMath64x64.add(0x413c831bb169f874, ABDKMath64x64.mul(t, ABDKMath64x64.add(-0x48d4c730f051a5fe, f)));
return
ABDKMath64x64.sub(
0x10000000000000000,
ABDKMath64x64.mul(
t,
ABDKMath64x64.mul(f2, ABDKMath64x64.exp(ABDKMath64x64.mul(ABDKMath64x64.neg(z), z)))
)
);
}
/**
* @dev Private function to calculate the rate factor: e ^ (-rate * expiration).
* @param rate The rate normalized with `ABDKMath64x64` library.
* @param expiration The expiration annual equivalent percentage normalized with `ABDKMath64x64` library.
* @return The rate factor normalized with `ABDKMath64x64` library.
*/
function _getRateFactor(int128 rate, int128 expiration) private pure returns (int128) {
int128 rateFactor = 0x10000000000000000;
if (rate > 0) {
rateFactor = ABDKMath64x64.exp(ABDKMath64x64.mul(ABDKMath64x64.neg(rate), expiration));
}
return rateFactor;
}
/**
* @dev Private function to calculate the D1 data for the Black-Sholes method.
* @param strikePrice The strike price normalized with `ABDKMath64x64` library.
* @param currentPrice The current underlying price normalized with `ABDKMath64x64` library.
* @param expiration The expiration annual equivalent percentage normalized with `ABDKMath64x64` library.
* @param volatility The annual volatility normalized with `ABDKMath64x64` library.
* @param interestRate The annual interest rate normalized with `ABDKMath64x64` library.
* @param dividendYield The annual dividen yield normalized with `ABDKMath64x64` library.
* @param dCalculationAux The annual dividen yield normalized with `ABDKMath64x64` library.
* @return The D1 normalized with `ABDKMath64x64` library.
*/
function _d1Calculation(
int128 strikePrice,
int128 currentPrice,
int128 expiration,
int128 volatility,
int128 interestRate,
int128 dividendYield,
int128 dCalculationAux
) private pure returns (int128) {
return
ABDKMath64x64.div(
ABDKMath64x64.add(
ABDKMath64x64.ln(ABDKMath64x64.div(currentPrice, strikePrice)),
ABDKMath64x64.mul(
expiration,
ABDKMath64x64.add(
ABDKMath64x64.sub(interestRate, dividendYield),
ABDKMath64x64.div(ABDKMath64x64.mul(volatility, volatility), 0x20000000000000000)
)
)
),
dCalculationAux
);
}
}
| Private function to calculate the normal cummulative distribution. x The value normalized with `ABDKMath64x64` library to be calculated. return The normal cummulative distribution normalized with `ABDKMath64x64` library./ | function _normalCummulativeDistribution(int128 x) private pure returns (int128) {
int128 z = ABDKMath64x64.div(x, 0x16a09e667f3bcc908);
int128 t =
ABDKMath64x64.div(
0x10000000000000000,
ABDKMath64x64.add(0x10000000000000000, ABDKMath64x64.mul(0x53dd02a4f5ee2e46, ABDKMath64x64.abs(z)))
);
int128 erf = _getErf(z, t);
int128 nerf = erf;
if (z < 0) {
nerf = ABDKMath64x64.neg(erf);
}
return ABDKMath64x64.mul(0x8000000000000000, ABDKMath64x64.add(0x10000000000000000, nerf));
}
| 927,923 |
./full_match/11155111/0xEcbF5BfAeD62D9862e05F5762A46004CB9ff515B/sources/contracts/CrowdFunding.sol | Comment to a Project | function donateToCampaign(
uint256 _campaignId,
string memory _message
) public payable {
uint256 amount = msg.value;
Donate storage donate = donations[numberOfDonations];
numberOfDonations++;
donate.id = numberOfDonations;
donate.campaignId = _campaignId;
donate.donator = msg.sender;
donate.amount = amount;
donate.message = _message;
donate.createdAt = block.timestamp;
Campaign storage campaign = campaigns[_campaignId];
if (sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
| 3,795,993 |
pragma solidity ^0.6.7;
contract Shard {
/// @notice EIP-20 token name for this token
string public constant name = "Shard";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "SHARD";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 80_000_000e18; // 80 million Shard
/// @notice Limit on the totalSupply that can be minted
uint96 public constant maxSupply = 210_000_000e18; // 210 million Shard
/// @notice Address which may mint new tokens
address public minter;
/// @notice The timestamp after which minting may occur
uint public mintingAllowedAfter;
/// @notice Minimum time between mints
uint32 public constant minimumTimeBetweenMints = 183 days;
/// @dev Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @dev 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 The EIP-712 typehash for the transfer struct used by the contract
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address to,uint256 value,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the transferWithFee struct used by the contract
bytes32 public constant TRANSFER_WITH_FEE_TYPEHASH = keccak256("TransferWithFee(address to,uint256 value,uint256 fee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) 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, uint previousBalance, uint 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 Shard token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
* @param mintingAllowedAfter_ The timestamp after which minting may occur
*/
constructor(address account, address minter_, uint mintingAllowedAfter_) public {
require(mintingAllowedAfter_ >= block.timestamp, "Shard::constructor: minting can only begin after deployment");
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter_);
mintingAllowedAfter = mintingAllowedAfter_;
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(msg.sender == minter, "Shard::setMinter: only the minter can change the minter address");
require(minter_ != address(0), "Shard::setMinter: cannot set minter to the zero 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, uint rawAmount) external {
require(msg.sender == minter, "Shard::mint: only the minter can mint");
require(block.timestamp >= mintingAllowedAfter, "Shard::mint: minting not allowed yet");
require(dst != address(0), "Shard::mint: cannot transfer to the zero address");
// record the mint
mintingAllowedAfter = add256(block.timestamp, minimumTimeBetweenMints, "Shard::mint: mintingAllowedAfter overflows");
// mint the amount
uint96 amount = safe96(rawAmount, "Shard::mint: amount exceeds 96 bits");
uint _totalSupply = totalSupply;
require(amount <= _totalSupply / 100, "Shard::mint: amount exceeds mint allowance");
_totalSupply = add256(_totalSupply, amount, "Shard::mint: totalSupply overflows");
require(_totalSupply <= maxSupply, "Shard::mint: totalSupply exceeds maxSupply");
totalSupply = _totalSupply;
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "Shard::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @notice Burn `amount` tokens from `msg.sender`
* @param rawAmount The number of tokens to burn
* @return Whether or not the burn succeeded
*/
function burn(uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::burn: amount exceeds 96 bits");
_burnTokens(msg.sender, amount);
return true;
}
/**
* @notice Burn `amount` tokens from `src`
* @param src The address of the source account
* @param rawAmount The number of tokens to burn
* @return Whether or not the burn succeeded
*/
function burnFrom(address src, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::burnFrom: amount exceeds 96 bits");
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Shard::burnFrom: amount exceeds spender allowance");
_approve(src, spender, newAllowance);
}
_burnTokens(src, amount);
return true;
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Shard::approve: amount exceeds 96 bits");
}
_approve(msg.sender, spender, amount);
return true;
}
/**
* @notice Approve `spender` to transfer `amount` extra from `src`
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens to increase the approval by
* @return Whether or not the approval succeeded
*/
function increaseAllowance(address spender, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::increaseAllowance: amount exceeds 96 bits");
uint96 newAllowance = add96(allowances[msg.sender][spender], amount, "Shard::increaseAllowance: allowance overflows");
_approve(msg.sender, spender, newAllowance);
return true;
}
/**
* @notice Approve `spender` to transfer `amount` less from `src`
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens to decrease the approval by
* @return Whether or not the approval succeeded
*/
function decreaseAllowance(address spender, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::decreaseAllowance: amount exceeds 96 bits");
uint96 newAllowance = sub96(allowances[msg.sender][spender], amount, "Shard::decreaseAllowance: allowance underflows");
_approve(msg.sender, spender, newAllowance);
return true;
}
/**
* @notice Triggers an approval from owner to spender
* @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, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Shard::permit: amount exceeds 96 bits");
}
require(block.timestamp <= deadline, "Shard::permit: signature expired");
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
address signatory = ecrecover(getDigest(structHash), v, r, s);
require(signatory != address(0), "Shard::permit: invalid signature");
require(signatory == owner, "Shard::permit: unauthorized");
return _approve(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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::transfer: 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, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Shard::transferFrom: amount exceeds 96 bits");
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Shard::transferFrom: amount exceeds spender allowance");
_approve(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Transfer various `amount` tokens from `msg.sender` to `dsts`
* @param dsts The addresses of the destination accounts
* @param rawAmounts The numbers of tokens to transfer
* @return Whether or not the transfers succeeded
*/
function transferBatch(address[] calldata dsts, uint[] calldata rawAmounts) external returns (bool) {
uint length = dsts.length;
require(length == rawAmounts.length, "Shard::transferBatch: calldata arrays must have the same length");
for (uint i = 0; i < length; i++) {
uint96 amount = safe96(rawAmounts[i], "Shard::transferBatch: amount exceeds 96 bits");
_transferTokens(msg.sender, dsts[i], amount);
}
return true;
}
/**
* @notice Transfer `amount` tokens from signatory to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @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 transferBySig(address dst, uint rawAmount, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount = safe96(rawAmount, "Shard::transferBySig: amount exceeds 96 bits");
require(block.timestamp <= expiry, "Shard::transferBySig: signature expired");
bytes32 structHash = keccak256(abi.encode(TRANSFER_TYPEHASH, dst, rawAmount, nonce, expiry));
address signatory = ecrecover(getDigest(structHash), v, r, s);
require(signatory != address(0), "Shard::transferBySig: invalid signature");
require(nonce == nonces[signatory]++, "Shard::transferBySig: invalid nonce");
return _transferTokens(signatory, dst, amount);
}
/**
* @notice Transfer `amount` tokens from signatory to `dst` with 'fee' tokens to 'feeTo'
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @param rawFee The number of tokens to transfer as fee
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param feeTo The address of the fee recipient account chosen by the msg.sender
* @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 transferWithFeeBySig(address dst, uint rawAmount, uint rawFee, uint nonce, uint expiry, address feeTo, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount = safe96(rawAmount, "Shard::transferWithFeeBySig: amount exceeds 96 bits");
uint96 fee = safe96(rawFee, "Shard::transferWithFeeBySig: fee exceeds 96 bits");
require(block.timestamp <= expiry, "Shard::transferWithFeeBySig: signature expired");
bytes32 structHash = keccak256(abi.encode(TRANSFER_WITH_FEE_TYPEHASH, dst, rawAmount, rawFee, nonce, expiry));
address signatory = ecrecover(getDigest(structHash), v, r, s);
require(signatory != address(0), "Shard::transferWithFeeBySig: invalid signature");
require(nonce == nonces[signatory]++, "Shard::transferWithFeeBySig: invalid nonce");
_transferTokens(signatory, feeTo, fee);
return _transferTokens(signatory, dst, amount);
}
/**
* @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, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
require(block.timestamp <= expiry, "Shard::delegateBySig: signature expired");
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
address signatory = ecrecover(getDigest(structHash), v, r, s);
require(signatory != address(0), "Shard::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Shard::delegateBySig: invalid nonce");
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, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Shard::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _approve(address owner, address spender, uint96 amount) internal {
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnTokens(address src, uint96 amount) internal {
require(src != address(0), "Shard::_burnTokens: cannot transfer from the zero address");
balances[src] = sub96(balances[src], amount, "Shard::_burnTokens: transfer amount exceeds balance");
totalSupply -= amount; // no case where balance exceeds totalSupply
emit Transfer(src, address(0), amount);
_moveDelegates(delegates[src], address(0), amount);
}
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), "Shard::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Shard::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Shard::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Shard::_transferTokens: 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, "Shard::_moveVotes: 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, "Shard::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Shard::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint 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 c) {
require((c = a + b) >= a, errorMessage);
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function add256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256 c) {
require((c = a + b) >= a, errorMessage);
}
function getDigest(bytes32 structHash) internal view returns (bytes32) {
uint256 chainId;
assembly { chainId := chainid() }
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), chainId, address(this)));
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
} | Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens rawAmount The number of tokens that are approved (2^256-1 means infinite) return Whether or not the approval succeeded/ | function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "Shard::approve: amount exceeds 96 bits");
}
_approve(msg.sender, spender, amount);
return true;
}
| 5,874,386 |
./full_match/43114/0xD97B4D013b31df04b6917Dc318D3197169c36bFD/sources/contracts/LongShort.sol | Transfers outstanding synth tokens from a next price mint to the user. The outstanding synths should already be reflected for the user due to balanceOf in SyntheticToken.sol, this just does the accounting. marketIndex An uint32 which uniquely identifies a market. user The address of the user for whom to execute the function for. isLong Whether this is for the long or short synth for the market. | function _executeOutstandingNextPriceMints(
uint32 marketIndex,
address user,
bool isLong
) internal virtual {
uint256 currentPaymentTokenDepositAmount = userNextPrice_paymentToken_depositAmount[
marketIndex
][isLong][user];
if (currentPaymentTokenDepositAmount > 0) {
userNextPrice_paymentToken_depositAmount[marketIndex][isLong][user] = 0;
uint256 amountSyntheticTokensToTransferToUser = _getAmountSyntheticToken(
currentPaymentTokenDepositAmount,
syntheticToken_priceSnapshot[marketIndex][isLong][
userNextPrice_currentUpdateIndex[marketIndex][user]
]
);
ISyntheticToken(syntheticTokens[marketIndex][isLong]).transfer(
user,
amountSyntheticTokensToTransferToUser
);
}
}
| 4,519,998 |
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/dependencies/uniswapv3-core/UniswapV3Pool.sol | Common checks for valid tick inputs. | function checkTicks(int24 tickLower, int24 tickUpper) private pure {
if (tickLower >= tickUpper) revert TLU();
if (tickLower < TickMath.MIN_TICK) revert TLM();
if (tickUpper > TickMath.MAX_TICK) revert TUM();
}
| 4,203,062 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../libs/BaseRelayRecipient.sol";
interface ICitadelStrategy {
function getCurrentPool() external view returns (uint256);
function invest(uint256 _amount) external;
function yield() external;
function withdraw(uint256 _amount) external;
function reimburse() external;
function setAdmin(address _admin) external;
function setStrategist(address _strategist) external;
function emergencyWithdraw() external;
function reinvest() external;
}
interface IRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint[] memory amounts);
}
interface ICurveSwap {
function exchange(int128 i, int128 j, uint256 _dx, uint256 _min_dy) external;
}
interface IChainlink {
function latestAnswer() external view returns (int256);
}
contract CitadelVault is ERC20("DAO Vault Citadel", "daoCDV"), Ownable, BaseRelayRecipient {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Token {
IERC20 token;
uint256 decimals;
uint256 percKeepInVault;
}
IERC20 private constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
ICitadelStrategy public strategy;
IRouter private constant router = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
ICurveSwap private constant c3pool = ICurveSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
uint256 private constant DENOMINATOR = 10000;
address public pendingStrategy;
bool public canSetPendingStrategy;
uint256 public unlockTime;
uint256 public constant LOCKTIME = 2 days;
// Calculation for fees
uint256[] public networkFeeTier2 = [50000*1e18+1, 100000*1e18];
uint256 public customNetworkFeeTier = 1000000*1e18;
uint256[] public networkFeePerc = [100, 75, 50];
uint256 public customNetworkFeePerc = 25;
uint256 public profitSharingFeePerc = 2000;
uint256 private _fees; // 18 decimals
// Address to collect fees
address public treasuryWallet;
address public communityWallet;
address public admin;
address public strategist;
mapping(address => uint256) public _balanceOfDeposit; // Record deposit amount (USD in 18 decimals)
mapping(uint256 => Token) private Tokens;
event Deposit(address indexed tokenDeposit, address caller, uint256 amtDeposit, uint256 sharesMint);
event Withdraw(address indexed tokenWithdraw, address caller, uint256 amtWithdraw, uint256 sharesBurn);
event TransferredOutFees(uint256 fees);
event ETHToInvest(uint256 _balanceOfWETH);
event SetNetworkFeeTier2(uint256[] oldNetworkFeeTier2, uint256[] newNetworkFeeTier2);
event SetNetworkFeePerc(uint256[] oldNetworkFeePerc, uint256[] newNetworkFeePerc);
event SetCustomNetworkFeeTier(uint256 indexed oldCustomNetworkFeeTier, uint256 indexed newCustomNetworkFeeTier);
event SetCustomNetworkFeePerc(uint256 oldCustomNetworkFeePerc, uint256 newCustomNetworkFeePerc);
event SetProfitSharingFeePerc(uint256 indexed oldProfileSharingFeePerc, uint256 indexed newProfileSharingFeePerc);
event MigrateFunds(address indexed fromStrategy, address indexed toStrategy, uint256 amount);
modifier onlyAdmin {
require(msg.sender == address(admin), "Only admin");
_;
}
constructor(
address _strategy,
address _treasuryWallet, address _communityWallet,
address _admin, address _strategist,
address _biconomy
) {
strategy = ICitadelStrategy(_strategy);
treasuryWallet = _treasuryWallet;
communityWallet = _communityWallet;
admin = _admin;
strategist = _strategist;
trustedForwarder = _biconomy;
IERC20 USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
Tokens[0] = Token(USDT, 6, 200);
Tokens[1] = Token(USDC, 6, 200);
Tokens[2] = Token(DAI, 18, 200);
WETH.safeApprove(_strategy, type(uint256).max);
WETH.safeApprove(address(router), type(uint256).max);
USDT.safeApprove(address(router), type(uint256).max);
USDT.safeApprove(address(c3pool), type(uint256).max);
USDC.safeApprove(address(router), type(uint256).max);
USDC.safeApprove(address(c3pool), type(uint256).max);
DAI.safeApprove(address(router), type(uint256).max);
DAI.safeApprove(address(c3pool), type(uint256).max);
canSetPendingStrategy = true;
}
/// @notice Function that required for inherict BaseRelayRecipient
function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) {
return BaseRelayRecipient._msgSender();
}
/// @notice Function that required for inherict BaseRelayRecipient
function versionRecipient() external pure override returns (string memory) {
return "1";
}
/// @notice Function to deposit stablecoins
/// @param _amount Amount to deposit
/// @param _tokenIndex Type of stablecoin to deposit
function deposit(uint256 _amount, uint256 _tokenIndex) external {
require(msg.sender == tx.origin || isTrustedForwarder(msg.sender), "Only EOA or Biconomy");
require(_amount > 0, "Amount must > 0");
uint256 _ETHPrice = _determineETHPrice(_tokenIndex);
uint256 _pool = getAllPoolInETH(_ETHPrice);
address _sender = _msgSender();
Tokens[_tokenIndex].token.safeTransferFrom(_sender, address(this), _amount);
uint256 _amtDeposit = _amount; // For event purpose
if (Tokens[_tokenIndex].decimals == 6) {
_amount = _amount.mul(1e12);
}
// Calculate network fee
uint256 _networkFeePerc;
if (_amount < networkFeeTier2[0]) {
// Tier 1
_networkFeePerc = networkFeePerc[0];
} else if (_amount <= networkFeeTier2[1]) {
// Tier 2
_networkFeePerc = networkFeePerc[1];
} else if (_amount < customNetworkFeeTier) {
// Tier 3
_networkFeePerc = networkFeePerc[2];
} else {
// Custom Tier
_networkFeePerc = customNetworkFeePerc;
}
uint256 _fee = _amount.mul(_networkFeePerc).div(DENOMINATOR);
_fees = _fees.add(_fee);
_amount = _amount.sub(_fee);
_balanceOfDeposit[_sender] = _balanceOfDeposit[_sender].add(_amount);
uint256 _amountInETH = _amount.mul(_ETHPrice).div(1e18);
uint256 _shares = totalSupply() == 0 ? _amountInETH : _amountInETH.mul(totalSupply()).div(_pool);
_mint(_sender, _shares);
emit Deposit(address(Tokens[_tokenIndex].token), _sender, _amtDeposit, _shares);
}
/// @notice Function to withdraw
/// @param _shares Amount of shares to withdraw (from LP token, 18 decimals)
/// @param _tokenIndex Type of stablecoin to withdraw
function withdraw(uint256 _shares, uint256 _tokenIndex) external {
require(msg.sender == tx.origin, "Only EOA");
require(_shares > 0, "Shares must > 0");
uint256 _totalShares = balanceOf(msg.sender);
require(_totalShares >= _shares, "Insufficient balance to withdraw");
// Calculate deposit amount
uint256 _depositAmt = _balanceOfDeposit[msg.sender].mul(_shares).div(_totalShares);
// Subtract deposit amount
_balanceOfDeposit[msg.sender] = _balanceOfDeposit[msg.sender].sub(_depositAmt);
// Calculate withdraw amount
uint256 _ETHPrice = _determineETHPrice(_tokenIndex);
uint256 _withdrawAmt = getAllPoolInETH(_ETHPrice).mul(_shares).div(totalSupply());
_burn(msg.sender, _shares);
uint256 _withdrawAmtInUSD = _withdrawAmt.mul(_getPriceFromChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419)).div(1e8); // ETH/USD
Token memory _token = Tokens[_tokenIndex];
uint256 _balanceOfToken = _token.token.balanceOf(address(this));
// Change _balanceOfToken to 18 decimals same as _withdrawAmtInUSD
if (_token.decimals == 6) {
_balanceOfToken = _balanceOfToken.mul(1e12);
}
if (_withdrawAmtInUSD > _balanceOfToken) {
// Not enough stablecoin in vault, need to get from strategy
strategy.withdraw(_withdrawAmt);
uint256[] memory _amounts = _swapExactTokensForTokens(WETH.balanceOf(address(this)), address(WETH), address(_token.token));
// Change withdraw amount to 18 decimals if not DAI (for calculate profit sharing fee)
_withdrawAmtInUSD = _token.decimals == 6 ? _amounts[1].mul(1e12) : _amounts[1];
}
// Calculate profit sharing fee
if (_withdrawAmtInUSD > _depositAmt) {
uint256 _profit = _withdrawAmtInUSD.sub(_depositAmt);
uint256 _fee = _profit.mul(profitSharingFeePerc).div(DENOMINATOR);
_withdrawAmtInUSD = _withdrawAmtInUSD.sub(_fee);
_fees = _fees.add(_fee);
}
// Change back withdraw amount to 6 decimals if not DAI
if (_token.decimals == 6) {
_withdrawAmtInUSD = _withdrawAmtInUSD.div(1e12);
}
_token.token.safeTransfer(msg.sender, _withdrawAmtInUSD);
emit Withdraw(address(Tokens[_tokenIndex].token), msg.sender, _withdrawAmtInUSD, _shares);
}
/// @notice Function to invest funds into strategy
function invest() external onlyAdmin {
Token memory _USDT = Tokens[0];
Token memory _USDC = Tokens[1];
Token memory _DAI = Tokens[2];
// Transfer out network fees
_fees = _fees.div(1e12); // Convert to USDT decimals
if (_fees != 0 && _USDT.token.balanceOf(address(this)) > _fees) {
uint256 _treasuryFee = _fees.mul(2).div(5); // 40%
_USDT.token.safeTransfer(treasuryWallet, _treasuryFee); // 40%
_USDT.token.safeTransfer(communityWallet, _treasuryFee); // 40%
_USDT.token.safeTransfer(strategist, _fees.sub(_treasuryFee).sub(_treasuryFee)); // 20%
emit TransferredOutFees(_fees);
_fees = 0;
}
uint256 _poolInUSD = getAllPoolInUSD().sub(_fees);
// Calculation for keep portion of stablecoins and swap remainder to WETH
uint256 _toKeepUSDT = _poolInUSD.mul(_USDT.percKeepInVault).div(DENOMINATOR);
uint256 _toKeepUSDC = _poolInUSD.mul(_USDC.percKeepInVault).div(DENOMINATOR);
uint256 _toKeepDAI = _poolInUSD.mul(_DAI.percKeepInVault).div(DENOMINATOR);
_invest(_USDT.token, _toKeepUSDT);
_invest(_USDC.token, _toKeepUSDC);
_toKeepDAI = _toKeepDAI.mul(1e12); // Follow decimals of DAI
_invest(_DAI.token, _toKeepDAI);
// Invest all swapped WETH to strategy
uint256 _balanceOfWETH = WETH.balanceOf(address(this));
if (_balanceOfWETH > 0) {
strategy.invest(_balanceOfWETH);
emit ETHToInvest(_balanceOfWETH);
}
}
/// @notice Function to swap stablecoin to WETH
/// @param _token Stablecoin to swap
/// @param _toKeepAmt Amount to keep in vault (decimals follow stablecoins)
function _invest(IERC20 _token, uint256 _toKeepAmt) private {
uint256 _balanceOfToken = _token.balanceOf(address(this));
if (_balanceOfToken > _toKeepAmt) {
_swapExactTokensForTokens(_balanceOfToken.sub(_toKeepAmt), address(_token), address(WETH));
}
}
/// @notice Function to yield farms reward in strategy
function yield() external onlyAdmin {
strategy.yield();
}
/// @notice Function to swap stablecoin within vault with Curve
/// @notice Amount to swap == amount to keep in vault of _tokenTo stablecoin
/// @param _tokenFrom Type of stablecoin to be swapped
/// @param _tokenTo Type of stablecoin to be received
/// @param _amount Amount to be swapped (follow stablecoins decimals)
function swapTokenWithinVault(uint256 _tokenFrom, uint256 _tokenTo, uint256 _amount) external onlyAdmin {
require(Tokens[_tokenFrom].token.balanceOf(address(this)) > _amount, "Insufficient amount to swap");
int128 i = _determineCurveIndex(_tokenFrom);
int128 j = _determineCurveIndex(_tokenTo);
c3pool.exchange(i, j, _amount, 0);
}
/// @notice Function to determine Curve index for swapTokenWithinVault()
/// @param _tokenIndex Index of stablecoin
/// @return stablecoin index use in Curve
function _determineCurveIndex(uint256 _tokenIndex) private pure returns (int128) {
if (_tokenIndex == 0) {
return 2;
} else if (_tokenIndex == 1) {
return 1;
} else {
return 0;
}
}
/// @notice Function to reimburse keep Tokens from strategy
/// @notice This function remove liquidity from all strategy farm and will cost massive gas fee. Only call when needed.
function reimburseTokenFromStrategy() external onlyAdmin {
strategy.reimburse();
}
/// @notice Function to withdraw all farms and swap to WETH in strategy
function emergencyWithdraw() external onlyAdmin {
strategy.emergencyWithdraw();
}
/// @notice Function to reinvest all WETH back to farms in strategy
function reinvest() external onlyAdmin {
strategy.reinvest();
}
/// @notice Function to swap between tokens with Uniswap
/// @param _amountIn Amount to swap
/// @param _fromToken Token to be swapped
/// @param _toToken Token to be received
/// @return _amounts Array that contain amount swapped
function _swapExactTokensForTokens(uint256 _amountIn, address _fromToken, address _toToken) private returns (uint256[] memory _amounts) {
address[] memory _path = new address[](2);
_path[0] = _fromToken;
_path[1] = _toToken;
uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path);
if (_amountsOut[1] > 0) {
_amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp);
} else {
// Not enough amount to swap
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[1] = 0;
return _zeroReturn;
}
}
/// @notice Function to set new network fee for deposit amount tier 2
/// @param _networkFeeTier2 Array that contains minimum and maximum amount of tier 2 (18 decimals)
function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner {
require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0");
require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must greater than minimun amount");
/**
* Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2
* Tier 1: deposit amount < minimun amount of tier 2
* Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2
* Tier 3: amount > maximun amount of tier 2
*/
uint256[] memory oldNetworkFeeTier2 = networkFeeTier2;
networkFeeTier2 = _networkFeeTier2;
emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2);
}
/// @notice Function to set new custom network fee tier
/// @param _customNetworkFeeTier Amount of new custom network fee tier (18 decimals)
function setCustomNetworkFeeTier(uint256 _customNetworkFeeTier) external onlyOwner {
require(_customNetworkFeeTier > networkFeeTier2[1], "Custom network fee tier must greater than tier 2");
uint256 oldCustomNetworkFeeTier = customNetworkFeeTier;
customNetworkFeeTier = _customNetworkFeeTier;
emit SetCustomNetworkFeeTier(oldCustomNetworkFeeTier, _customNetworkFeeTier);
}
/// @notice Function to set new network fee percentage
/// @param _networkFeePerc Array that contains new network fee percentage for tier 1, tier 2 and tier 3
function setNetworkFeePerc(uint256[] calldata _networkFeePerc) external onlyOwner {
require(
_networkFeePerc[0] < 3000 &&
_networkFeePerc[1] < 3000 &&
_networkFeePerc[2] < 3000,
"Network fee percentage cannot be more than 30%"
);
/**
* _networkFeePerc content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3
* For example networkFeePerc is [100, 75, 50]
* which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5%
*/
uint256[] memory oldNetworkFeePerc = networkFeePerc;
networkFeePerc = _networkFeePerc;
emit SetNetworkFeePerc(oldNetworkFeePerc, _networkFeePerc);
}
/// @notice Function to set new custom network fee percentage
/// @param _percentage Percentage of new custom network fee
function setCustomNetworkFeePerc(uint256 _percentage) public onlyOwner {
require(_percentage < networkFeePerc[2], "Custom network fee percentage cannot be more than tier 2");
uint256 oldCustomNetworkFeePerc = customNetworkFeePerc;
customNetworkFeePerc = _percentage;
emit SetCustomNetworkFeePerc(oldCustomNetworkFeePerc, _percentage);
}
/// @notice Function to set new profit sharing fee percentage
/// @param _percentage Percentage of new profit sharing fee
function setProfitSharingFeePerc(uint256 _percentage) external onlyOwner {
require(_percentage < 3000, "Profile sharing fee percentage cannot be more than 30%");
uint256 oldProfitSharingFeePerc = profitSharingFeePerc;
profitSharingFeePerc = _percentage;
emit SetProfitSharingFeePerc(oldProfitSharingFeePerc, _percentage);
}
/// @notice Function to set new treasury wallet address
/// @param _treasuryWallet Address of new treasury wallet
function setTreasuryWallet(address _treasuryWallet) external onlyOwner {
treasuryWallet = _treasuryWallet;
}
/// @notice Function to set new community wallet address
/// @param _communityWallet Address of new community wallet
function setCommunityWallet(address _communityWallet) external onlyOwner {
communityWallet = _communityWallet;
}
/// @notice Function to set new admin address
/// @param _admin Address of new admin
function setAdmin(address _admin) external onlyOwner {
admin = _admin;
strategy.setAdmin(_admin);
}
/// @notice Function to set new strategist address
/// @param _strategist Address of new strategist
function setStrategist(address _strategist) external {
require(msg.sender == strategist || msg.sender == owner(), "Not authorized");
strategist = _strategist;
strategy.setStrategist(_strategist);
}
/// @notice Function to set pending strategy address
/// @param _pendingStrategy Address of pending strategy
function setPendingStrategy(address _pendingStrategy) external onlyOwner {
require(canSetPendingStrategy, "Cannot set pending strategy now");
pendingStrategy = _pendingStrategy;
}
/// @notice Function to set new trusted forwarder address (Biconomy)
/// @param _biconomy Address of new trusted forwarder
function setBiconomy(address _biconomy) external onlyOwner {
trustedForwarder = _biconomy;
}
/// @notice Function to set percentage of stablecoins that keep in vault
/// @param _percentages Array with new percentages of stablecoins that keep in vault
function setPercTokenKeepInVault(uint256[] memory _percentages) external onlyAdmin {
Tokens[0].percKeepInVault = _percentages[0];
Tokens[1].percKeepInVault = _percentages[1];
Tokens[2].percKeepInVault = _percentages[2];
}
/// @notice Function to unlock migrate funds function
function unlockMigrateFunds() external onlyOwner {
unlockTime = block.timestamp.add(LOCKTIME);
canSetPendingStrategy = false;
}
/// @notice Function to migrate all funds from old strategy contract to new strategy contract
function migrateFunds() external onlyOwner {
require(unlockTime <= block.timestamp && unlockTime.add(1 days) >= block.timestamp, "Function locked");
require(WETH.balanceOf(address(strategy)) > 0, "No balance to migrate");
require(pendingStrategy != address(0), "No pendingStrategy");
uint256 _amount = WETH.balanceOf(address(strategy));
WETH.safeTransferFrom(address(strategy), pendingStrategy, _amount);
// Set new strategy
address oldStrategy = address(strategy);
strategy = ICitadelStrategy(pendingStrategy);
pendingStrategy = address(0);
canSetPendingStrategy = true;
// Approve new strategy
WETH.safeApprove(address(strategy), type(uint256).max);
WETH.safeApprove(oldStrategy, 0);
unlockTime = 0; // Lock back this function
emit MigrateFunds(oldStrategy, address(strategy), _amount);
}
/// @notice Function to get all pool amount(vault+strategy) in USD (use USDT/ETH as price feed)
/// @return All pool in USD (6 decimals follow USDT)
function getAllPoolInUSD() public view returns (uint256) {
uint256 _currentETHprice = _getPriceFromChainlink(0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46); // USDT/ETH
uint256 _currentUSDprice = _getPriceFromChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // ETH/USD
return getAllPoolInETH(_currentETHprice).mul(_currentUSDprice).div(1e20);
}
/// @notice Same as getAllPoolInETH() above with parameter
/// @param _price ETH price from ChainLink (USDT/ETH)
/// @return All pool in ETH (18 decimals)
function getAllPoolInETH(uint256 _price) public view returns (uint256) {
uint256 _vaultPoolInETH = _getVaultPoolInUSD().mul(_price);
return strategy.getCurrentPool().add(_vaultPoolInETH);
}
/// @notice Function to get exact USD amount of pool in vault
/// @return Exact USD amount of pool in vault (no decimals)
function _getVaultPoolInUSD() private view returns (uint256) {
uint256 _vaultPoolInUSD = (Tokens[0].token.balanceOf(address(this)).mul(1e12))
.add(Tokens[1].token.balanceOf(address(this)).mul(1e12))
.add(Tokens[2].token.balanceOf(address(this)))
.sub(_fees);
// In very rare case that fees > vault pool, above calculation will raise error
// Use getReimburseTokenAmount() to get some stablecoin from strategy
return _vaultPoolInUSD.div(1e18);
}
/// @notice Function to get price from ChainLink contract
/// @param _priceFeedProxy Address of ChainLink contract that provide price
/// @return Price (8 decimals for USD, 18 decimals for ETH)
function _getPriceFromChainlink(address _priceFeedProxy) private view returns (uint256) {
IChainlink _pricefeed = IChainlink(_priceFeedProxy);
int256 _price = _pricefeed.latestAnswer();
return uint256(_price);
}
/// @notice Function to determine ETH price based on stablecoin
/// @param _tokenIndex Type of stablecoin to determine
/// @return Price of ETH (18 decimals)
function _determineETHPrice(uint256 _tokenIndex) private view returns (uint256) {
address _priceFeedContract;
if (address(Tokens[_tokenIndex].token) == 0xdAC17F958D2ee523a2206206994597C13D831ec7) { // USDT
_priceFeedContract = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT/ETH
} else if (address(Tokens[_tokenIndex].token) == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) { // USDC
_priceFeedContract = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC/ETH
} else { // DAI
_priceFeedContract = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI/ETH
}
return _getPriceFromChainlink(_priceFeedContract);
}
/// @notice Function to get amount need to fill up minimum amount keep in vault
/// @param _tokenIndex Type of stablecoin requested
/// @return Amount to reimburse (USDT, USDC 6 decimals, DAI 18 decimals)
function getReimburseTokenAmount(uint256 _tokenIndex) public view returns (uint256) {
Token memory _token = Tokens[_tokenIndex];
uint256 _toKeepAmt = getAllPoolInUSD().mul(_token.percKeepInVault).div(DENOMINATOR);
if (_token.decimals == 18) {
_toKeepAmt = _toKeepAmt.mul(1e12);
}
uint256 _balanceOfToken = _token.token.balanceOf(address(this));
if (_balanceOfToken < _toKeepAmt) {
return _toKeepAmt.sub(_balanceOfToken);
}
return 0; // amount keep in vault is full
}
}
// 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 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;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier:MIT
pragma solidity 0.7.6;
import "../interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
/*
* require a function to be called through GSN only
*/
modifier trustedForwarderOnly() {
require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder");
_;
}
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
}
// 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: 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.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
function versionRecipient() external virtual view returns (string memory);
}
| Function to set pending strategy address _pendingStrategy Address of pending strategy | function setPendingStrategy(address _pendingStrategy) external onlyOwner {
require(canSetPendingStrategy, "Cannot set pending strategy now");
pendingStrategy = _pendingStrategy;
}
| 13,715,949 |
/**
*Submitted for verification at Etherscan.io on 2020-05-29
*/
pragma solidity ^0.5.0;
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 Context {
constructor () internal { }
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;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is Context, ERC20{
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
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;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
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;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
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;
}
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;
}
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);
}
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);
}
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");
allowed[owner][_spender] = amount;
emit Approval(owner, _spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, allowed[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
event NotPausable();
bool public paused = false;
bool public canPause = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused || msg.sender == owner);
_;
}
/**
* @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 {
require(canPause == true);
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
require(paused == true);
paused = false;
emit Unpause();
}
/**
* @dev Prevent the token from ever being paused again
**/
function notPausable() onlyOwner public{
paused = false;
canPause = false;
emit NotPausable();
}
}
contract Mintable is BasicToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract ERC20Burnable is Context, BasicToken {
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
contract ERC20Detailed is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract PausableToken is BasicToken, ERC20Detailed, Pausable, ERC20Burnable, Mintable {
string public constant NAME = "beautyon";
string public constant SYMBOL = "bto";
uint256 public constant DECIMALS = 8;
uint256 public constant INITIAL_SUPPLY = 2000000000 * 10**8;
/**
* @dev Transfer tokens when not paused
**/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev transferFrom function to tansfer tokens when token is not paused
**/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev approve spender when not paused
**/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
/**
* @dev increaseApproval of spender when not paused
**/
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev decreaseApproval of spender when not paused
**/
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* Pausable Token Constructor
* @dev Create and issue tokens to msg.sender.
*/
/*
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
*/
constructor () public ERC20Detailed("beautyon", "bto", 8) {
_mint(0x068aeb16e5Bb1F1743Fe515D0FC77C5e81d3C8D2, 2000000000 * (10 ** uint256(decimals())));
}
} | transferFrom function to tansfer tokens when token is not paused/ | function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
| 168,744 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
}
/**
* @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
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @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 An 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 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) {
_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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(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) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @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
* 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @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
* 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
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 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 {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// The functionality that all derivative contracts expose to the admin.
interface AdminInterface {
// Initiates the shutdown process, in case of an emergency.
function emergencyShutdown() external;
// A core contract method called immediately before or after any financial transaction. It pays fees and moves money
// between margin accounts to make sure they reflect the NAV of the contract.
function remargin() external;
}
contract ExpandedIERC20 is IERC20 {
// Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless.
function burn(uint value) external;
// Mints tokens and adds them to the balance of the `to` address.
// Note: this method should be permissioned to only allow designated parties to mint tokens.
function mint(address to, uint value) external;
}
// This interface allows derivative contracts to pay Oracle fees for their use of the system.
interface StoreInterface {
// Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH.
function payOracleFees() external payable;
// Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an
// ERC20 token rather than ETH. All approved tokens are transfered.
function payOracleFeesErc20(address erc20Address) external;
// Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the
// maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the
// price feed in their favor.
function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount);
}
interface ReturnCalculatorInterface {
// Computes the return between oldPrice and newPrice.
function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn);
// Gets the effective leverage for the return calculator.
// Note: if this parameter doesn't exist for this calculator, this method should return 1.
function leverage() external view returns (int _leverage);
}
// This interface allows contracts to query unverified prices.
interface PriceFeedInterface {
// Whether this PriceFeeds provides prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have
// been published for this identifier.
function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price);
// An event fired when a price is published.
event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price);
}
contract AddressWhitelist is Ownable {
enum Status { None, In, Out }
mapping(address => Status) private whitelist;
address[] private whitelistIndices;
// Adds an address to the whitelist
function addToWhitelist(address newElement) external onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddToWhitelist(newElement);
}
// Removes an address from the whitelist.
function removeFromWhitelist(address elementToRemove) external onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemoveFromWhitelist(elementToRemove);
}
}
// Checks whether an address is on the whitelist.
function isOnWhitelist(address elementToCheck) external view returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
// Gets all addresses that are currently included in the whitelist
// Note: This method skips over, but still iterates through addresses.
// It is possible for this call to run out of gas if a large number of
// addresses have been removed. To prevent this unlikely scenario, we can
// modify the implementation so that when addresses are removed, the last addresses
// in the array is moved to the empty index.
function getWhitelist() external view returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
event AddToWhitelist(address indexed addedAddress);
event RemoveFromWhitelist(address indexed removedAddress);
}
contract Withdrawable is Ownable {
// Withdraws ETH from the contract.
function withdraw(uint amount) external onlyOwner {
msg.sender.transfer(amount);
}
// Withdraws ERC20 tokens from the contract.
function withdrawErc20(address erc20Address, uint amount) external onlyOwner {
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
}
// This interface allows contracts to query a verified, trusted price.
interface OracleInterface {
// Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available.
// Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if
// the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this
// method.
function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime);
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable);
// Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if
// the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call
// this method.
function getPrice(bytes32 identifier, uint time) external view returns (int price);
// Returns whether the Oracle provides verified prices for the given identifier.
function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported);
// An event fired when a request for a (identifier, time) pair is made.
event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time);
// An event fired when a verified price is available for a (identifier, time) pair.
event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price);
}
interface RegistryInterface {
struct RegisteredDerivative {
address derivativeAddress;
address derivativeCreator;
}
// Registers a new derivative. Only authorized derivative creators can call this method.
function registerDerivative(address[] calldata counterparties, address derivativeAddress) external;
// Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call
// this method.
function addDerivativeCreator(address derivativeCreator) external;
// Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this
// method.
function removeDerivativeCreator(address derivativeCreator) external;
// Returns whether the derivative has been registered with the registry (and is therefore an authorized participant
// in the UMA system).
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered);
// Returns a list of all derivatives that are associated with a particular party.
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives);
// Returns all registered derivatives.
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives);
// Returns whether an address is authorized to register new derivatives.
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized);
}
contract Registry is RegistryInterface, Withdrawable {
using SafeMath for uint;
// Array of all registeredDerivatives that are approved to use the UMA Oracle.
RegisteredDerivative[] private registeredDerivatives;
// This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered.
enum PointerValidity {
Invalid,
Valid,
WasValid
}
struct Pointer {
PointerValidity valid;
uint128 index;
}
// Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives.
mapping(address => Pointer) private derivativePointers;
// Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied
// like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose
// of the Pointer struct and break separation of concern between referential data and data.
struct PartiesMap {
mapping(address => bool) parties;
}
// Maps from derivative address to the set of parties that are involved in that derivative.
mapping(address => PartiesMap) private derivativesToParties;
// Maps from derivative creator address to whether that derivative creator has been approved to register contracts.
mapping(address => bool) private derivativeCreators;
modifier onlyApprovedDerivativeCreator {
require(derivativeCreators[msg.sender]);
_;
}
function registerDerivative(address[] calldata parties, address derivativeAddress)
external
onlyApprovedDerivativeCreator
{
// Create derivative pointer.
Pointer storage pointer = derivativePointers[derivativeAddress];
// Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double
// registered).
require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender));
// No length check necessary because we should never hit (2^127 - 1) derivatives.
pointer.index = uint128(registeredDerivatives.length.sub(1));
// Set up PartiesMap for this derivative.
PartiesMap storage partiesMap = derivativesToParties[derivativeAddress];
for (uint i = 0; i < parties.length; i = i.add(1)) {
partiesMap.parties[parties[i]] = true;
}
address[] memory partiesForEvent = parties;
emit RegisterDerivative(derivativeAddress, partiesForEvent);
}
function addDerivativeCreator(address derivativeCreator) external onlyOwner {
if (!derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = true;
emit AddDerivativeCreator(derivativeCreator);
}
}
function removeDerivativeCreator(address derivativeCreator) external onlyOwner {
if (derivativeCreators[derivativeCreator]) {
derivativeCreators[derivativeCreator] = false;
emit RemoveDerivativeCreator(derivativeCreator);
}
}
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) {
return derivativePointers[derivative].valid == PointerValidity.Valid;
}
function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) {
// This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long
// as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy
// the array over to the return array, which is allocated using the correct size. Note: this is done by double
// copying each value rather than storing some referential info (like indices) in memory to reduce the number
// of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1).
RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length);
uint outputIndex = 0;
for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) {
RegisteredDerivative storage derivative = registeredDerivatives[i];
if (derivativesToParties[derivative.derivativeAddress].parties[party]) {
// Copy selected derivative to the temporary array.
tmpDerivativeArray[outputIndex] = derivative;
outputIndex = outputIndex.add(1);
}
}
// Copy the temp array to the return array that is set to the correct size.
derivatives = new RegisteredDerivative[](outputIndex);
for (uint j = 0; j < outputIndex; j = j.add(1)) {
derivatives[j] = tmpDerivativeArray[j];
}
}
function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) {
return registeredDerivatives;
}
function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) {
return derivativeCreators[derivativeCreator];
}
event RegisterDerivative(address indexed derivativeAddress, address[] parties);
event AddDerivativeCreator(address indexed addedDerivativeCreator);
event RemoveDerivativeCreator(address indexed removedDerivativeCreator);
}
contract Testable is Ownable {
// Is the contract being run on the test network. Note: this variable should be set on construction and never
// modified.
bool public isTest;
uint private currentTime;
constructor(bool _isTest) internal {
isTest = _isTest;
if (_isTest) {
currentTime = now; // solhint-disable-line not-rely-on-time
}
}
modifier onlyIfTest {
require(isTest);
_;
}
function setCurrentTime(uint _time) external onlyOwner onlyIfTest {
currentTime = _time;
}
function getCurrentTime() public view returns (uint) {
if (isTest) {
return currentTime;
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract ContractCreator is Withdrawable {
Registry internal registry;
address internal oracleAddress;
address internal storeAddress;
address internal priceFeedAddress;
constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress)
public
{
registry = Registry(registryAddress);
oracleAddress = _oracleAddress;
storeAddress = _storeAddress;
priceFeedAddress = _priceFeedAddress;
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
registry.registerDerivative(parties, contractToRegister);
}
}
library TokenizedDerivativeParams {
enum ReturnType {
Linear,
Compound
}
struct ConstructorParams {
address sponsor;
address admin;
address oracle;
address store;
address priceFeed;
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying price that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of margin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18
ReturnType returnType;
uint startingUnderlyingPrice;
uint creationTime;
}
}
// TokenizedDerivativeStorage: this library name is shortened due to it being used so often.
library TDS {
enum State {
// The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as
// it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state.
// Possible state transitions: Disputed, Expired, Defaulted.
Live,
// Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in
// time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn.
// The resolution of these states moves the contract to the Settled state. Remargining is not allowed.
// The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the
// Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short
// account. Otherwise, the dispute fee is added to the long margin account.
// Possible state transitions: Settled.
Disputed,
// Contract expiration has been reached.
// Possible state transitions: Settled.
Expired,
// The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and
// move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to
// Settled.
// Possible state transitions: Settled.
Defaulted,
// UMA has manually triggered a shutdown of the account.
// Possible state transitions: Settled.
Emergency,
// Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be
// created, and contract can't remargin.
// Possible state transitions: None.
Settled
}
// The state of the token at a particular time. The state gets updated on remargin.
struct TokenState {
int underlyingPrice;
int tokenPrice;
uint time;
}
// The information in the following struct is only valid if in the midst of a Dispute.
struct Dispute {
int disputedNav;
uint deposit;
}
struct WithdrawThrottle {
uint startTime;
uint remainingWithdrawal;
}
struct FixedParameters {
// Fixed contract parameters.
uint defaultPenalty; // Percentage of margin requirement * 10^18
uint supportedMove; // Expected percentage move that the long is protected against.
uint disputeDeposit; // Percentage of margin requirement * 10^18
uint fixedFeePerSecond; // Percentage of nav*10^18
uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18
bytes32 product;
TokenizedDerivativeParams.ReturnType returnType;
uint initialTokenUnderlyingRatio;
uint creationTime;
string symbol;
}
struct ExternalAddresses {
// Other addresses/contracts
address sponsor;
address admin;
address apDelegate;
OracleInterface oracle;
StoreInterface store;
PriceFeedInterface priceFeed;
ReturnCalculatorInterface returnCalculator;
IERC20 marginCurrency;
}
struct Storage {
FixedParameters fixedParameters;
ExternalAddresses externalAddresses;
// Balances
int shortBalance;
int longBalance;
State state;
uint endTime;
// The NAV of the contract always reflects the transition from (`prev`, `current`).
// In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev`
// and `latest` -> `current` (and then recompute).
// In the case of a dispute, `current` might change (which is why we have to hold on to `prev`).
TokenState referenceTokenState;
TokenState currentTokenState;
int nav; // Net asset value is measured in Wei
Dispute disputeInfo;
// Only populated once the contract enters a frozen state.
int defaultPenaltyAmount;
WithdrawThrottle withdrawThrottle;
}
}
library TokenizedDerivativeUtils {
using TokenizedDerivativeUtils for TDS.Storage;
using SafeMath for uint;
using SignedSafeMath for int;
uint private constant SECONDS_PER_DAY = 86400;
uint private constant SECONDS_PER_YEAR = 31536000;
uint private constant INT_MAX = 2**255 - 1;
uint private constant UINT_FP_SCALING_FACTOR = 10**18;
int private constant INT_FP_SCALING_FACTOR = 10**18;
modifier onlySponsor(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor);
_;
}
modifier onlyAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrAdmin(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin);
_;
}
modifier onlySponsorOrApDelegate(TDS.Storage storage s) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
_;
}
// Contract initializer. Should only be called at construction.
// Note: Must be a public function because structs cannot be passed as calldata (required data type for external
// functions).
function _initialize(
TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public {
s._setFixedParameters(params, symbol);
s._setExternalAddresses(params);
// Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally
// creating rounding or overflow errors.
require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9));
require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9));
// TODO(mrice32): we should have an ideal start time rather than blindly polling.
(uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
// If nonzero, take the user input as the starting price.
if (params.startingUnderlyingPrice != 0) {
latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice);
}
require(latestUnderlyingPrice > 0);
require(latestTime != 0);
// Keep the ratio in case it's needed for margin computation.
s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice));
require(s.fixedParameters.initialTokenUnderlyingRatio != 0);
// Set end time to max value of uint to implement no expiry.
if (params.expiry == 0) {
s.endTime = ~uint(0);
} else {
require(params.expiry >= latestTime);
s.endTime = params.expiry;
}
s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice);
s.state = TDS.State.Live;
}
function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
s._remarginInternal();
int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (newTokenNav < 0) {
newTokenNav = 0;
}
uint positiveTokenNav = _safeUintCast(newTokenNav);
// Get any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// Subtract newTokenNav from amount sent.
uint depositAmount = marginForPurchase.sub(positiveTokenNav);
// Deposit additional margin into the short account.
s._depositInternal(depositAmount);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund. This should be 0 in this case,
// but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure
// the sender never loses money.
refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external {
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
require(tokensToRedeem > 0);
if (s.state == TDS.State.Live) {
require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate);
s._remarginInternal();
require(s.state == TDS.State.Live);
}
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
uint initialSupply = _totalSupply();
require(initialSupply > 0);
_pullAuthorizedTokens(thisErc20Token, tokensToRedeem);
thisErc20Token.burn(tokensToRedeem);
emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem);
// Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor
// margin account.
uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply);
uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage);
s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin));
assert(s.longBalance >= 0);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
s._sendMargin(tokenMargin);
}
function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) {
require(
s.state == TDS.State.Live,
"Contract must be Live to dispute"
);
uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit));
uint sendInconsistencyRefund = s._pullSentMargin(depositMargin);
require(depositMargin >= requiredDeposit);
uint overpaymentRefund = depositMargin.sub(requiredDeposit);
s.state = TDS.State.Disputed;
s.endTime = s.currentTokenState.time;
s.disputeInfo.disputedNav = s.nav;
s.disputeInfo.deposit = requiredDeposit;
// Store the default penalty in case the dispute pushes the sponsor into default.
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav);
s._requestOraclePrice(s.endTime);
// Add the two types of refunds:
// 1. The refund for ETH sent if it was > depositMargin.
// 2. The refund for depositMargin > requiredDeposit.
s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund));
}
function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) {
// Remargin before allowing a withdrawal, but only if in the live state.
if (s.state == TDS.State.Live) {
s._remarginInternal();
}
// Make sure either in Live or Settled after any necessary remargin.
require(s.state == TDS.State.Live || s.state == TDS.State.Settled);
// If the contract has been settled or is in prefunded state then can
// withdraw up to full balance. If the contract is in live state then
// must leave at least the required margin. Not allowed to withdraw in
// other states.
int withdrawableAmount;
if (s.state == TDS.State.Settled) {
withdrawableAmount = s.shortBalance;
} else {
// Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit.
uint currentTime = s.currentTokenState.time;
if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) {
// We've passed the previous s.withdrawThrottle window. Start new one.
s.withdrawThrottle.startTime = currentTime;
s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit);
}
int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState));
int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal);
// Take the smallest of the two withdrawal limits.
withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw;
// Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above
// ternary is more explicit.
s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount);
}
// Can only withdraw the allowed amount.
require(
withdrawableAmount >= _safeIntCast(amount),
"Attempting to withdraw more than allowed"
);
// Transfer amount - Note: important to `-=` before the send so that the
// function can not be called multiple times while waiting for transfer
// to return.
s.shortBalance = s.shortBalance.sub(_safeIntCast(amount));
emit Withdrawal(s.fixedParameters.symbol, amount);
s._sendMargin(amount);
}
function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) {
// Right now, only confirming prices in the defaulted state.
require(s.state == TDS.State.Defaulted);
// Remargin on agreed upon price.
s._settleAgreedPrice();
}
function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) {
s.externalAddresses.apDelegate = _apDelegate;
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) {
require(s.state == TDS.State.Live);
s.state = TDS.State.Emergency;
s.endTime = s.currentTokenState.time;
s.defaultPenaltyAmount = s._computeDefaultPenalty();
emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime);
s._requestOraclePrice(s.endTime);
}
function _settle(TDS.Storage storage s) external {
s._settleInternal();
}
function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) {
// Returns any refund due to sending more margin than the argument indicated (should only be able to happen in
// the ETH case).
uint refund = s._pullSentMargin(marginForPurchase);
// The _createTokensInternal call returns any refund due to the amount sent being larger than the amount
// required to purchase the tokens, so we add that to the running refund.
refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase));
// Send the accumulated refund.
s._sendMargin(refund);
}
function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) {
// Only allow the s.externalAddresses.sponsor to deposit margin.
uint refund = s._pullSentMargin(marginToDeposit);
s._depositInternal(marginToDeposit);
// Send any refund due to sending more margin than the argument indicated (should only be able to happen in the
// ETH case).
s._sendMargin(refund);
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function _calcNAV(TDS.Storage storage s) external view returns (int navNew) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) {
(TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance();
newTokenValue = newTokenState.tokenPrice;
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) {
(, newShortMarginBalance) = s._calcNewTokenStateAndBalance();
}
function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) {
(TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance();
// If the contract is in/will be moved to a settled state, the margin requirement will be 0.
int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState);
return newShortMarginBalance.sub(requiredMargin);
}
function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) {
if (s.state == TDS.State.Settled) {
// No margin needs to be maintained when the contract is settled.
return 0;
}
return s._getRequiredMargin(s.currentTokenState);
}
function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) {
TDS.State currentState = s.state;
if (currentState == TDS.State.Settled) {
return false;
}
// Technically we should also check if price will default the contract, but that isn't a normal flow of
// operations that we want to simulate: we want to discourage the sponsor remargining into a default.
(uint priceFeedTime, ) = s._getLatestPrice();
if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) {
return false;
}
return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime);
}
function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) {
(TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance();
return (newTokenState.underlyingPrice, newTokenState.time);
}
function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance)
{
// TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted
// so the logic can be written once and used twice. However, much of this was written post-audit, so it was
// deemed preferable not to modify any state changing code that could potentially introduce new security
// bugs. This should be done before the next contract audit.
if (s.state == TDS.State.Settled) {
// If the contract is Settled, just return the current contract state.
return (s.currentTokenState, s.shortBalance);
}
// Grab the price feed pricetime.
(uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice();
bool isContractLive = s.state == TDS.State.Live;
bool isContractPostExpiry = priceFeedTime >= s.endTime;
// If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values.
if (isContractLive && priceFeedTime <= s.currentTokenState.time) {
return (s.currentTokenState, s.shortBalance);
}
// Determine which previous price state to use when computing the new NAV.
// If the contract is live, we use the reference for the linear return type or if the contract will immediately
// move to expiry.
bool shouldUseReferenceTokenState = isContractLive &&
(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry);
TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState;
// Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin.
(uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ?
(s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) :
(priceFeedTime, priceFeedPrice);
// Init the returned short balance to the current short balance.
newShortMarginBalance = s.shortBalance;
// Subtract the oracle fees from the short balance.
newShortMarginBalance = isContractLive ?
newShortMarginBalance.sub(
_safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) :
newShortMarginBalance;
// Compute the new NAV
newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime);
int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply());
newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance));
// If the contract is frozen or will move into expiry, we need to settle it, which means adding the default
// penalty and dispute deposit if necessary.
if (!isContractLive || isContractPostExpiry) {
// Subtract default penalty (if necessary) from the short balance.
bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState);
if (inDefault) {
int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty();
int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ?
newShortMarginBalance :
expectedDefaultPenalty;
newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty);
}
// Add the dispute deposit to the short balance if necessary.
if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
newShortMarginBalance = newShortMarginBalance.add(depositValue);
}
}
}
function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice)
internal
returns (int navNew)
{
int unitNav = _safeIntCast(startingTokenPrice);
s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime);
// Starting NAV is always 0 in the TokenizedDerivative case.
navNew = 0;
}
function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) {
s._remarginInternal();
}
function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) {
if(address(s.externalAddresses.marginCurrency) == erc20Address) {
uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this));
int totalBalances = s.shortBalance.add(s.longBalance);
assert(totalBalances >= 0);
uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit);
require(withdrawableAmount >= amount);
}
IERC20 erc20 = IERC20(erc20Address);
require(erc20.transfer(msg.sender, amount));
}
function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal {
// Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that
// tokens fail to conform is that they do not return a bool from certain state-changing operations. This
// contract was not designed to work with those tokens because of the additional complexity they would
// introduce.
s.externalAddresses.marginCurrency = IERC20(params.marginCurrency);
s.externalAddresses.oracle = OracleInterface(params.oracle);
s.externalAddresses.store = StoreInterface(params.store);
s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed);
s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator);
// Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product.
require(s.externalAddresses.oracle.isIdentifierSupported(params.product));
require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product));
s.externalAddresses.sponsor = params.sponsor;
s.externalAddresses.admin = params.admin;
}
function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal {
// Ensure only valid enum values are provided.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound
|| params.returnType == TokenizedDerivativeParams.ReturnType.Linear);
// Fee must be 0 if the returnType is linear.
require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0);
// The default penalty must be less than the required margin.
require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR);
s.fixedParameters.returnType = params.returnType;
s.fixedParameters.defaultPenalty = params.defaultPenalty;
s.fixedParameters.product = params.product;
s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR);
s.fixedParameters.disputeDeposit = params.disputeDeposit;
s.fixedParameters.supportedMove = params.supportedMove;
s.fixedParameters.withdrawLimit = params.withdrawLimit;
s.fixedParameters.creationTime = params.creationTime;
s.fixedParameters.symbol = symbol;
}
// _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for
// _remargin().
function _remarginInternal(TDS.Storage storage s) internal {
// If the state is not live, remargining does not make sense.
require(s.state == TDS.State.Live);
(uint latestTime, int latestPrice) = s._getLatestPrice();
// Checks whether contract has ended.
if (latestTime <= s.currentTokenState.time) {
// If the price feed hasn't advanced, remargining should be a no-op.
return;
}
// Save the penalty using the current state in case it needs to be used.
int potentialPenaltyAmount = s._computeDefaultPenalty();
if (latestTime >= s.endTime) {
s.state = TDS.State.Expired;
emit Expired(s.fixedParameters.symbol, s.endTime);
// Applies the same update a second time to effectively move the current state to the reference state.
int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time);
assert(recomputedNav == s.nav);
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime);
// Save the precomputed default penalty in case the expiry price pushes the sponsor into default.
s.defaultPenaltyAmount = potentialPenaltyAmount;
// We have no idea what the price was, exactly at s.endTime, so we can't set
// s.currentTokenState, or update the nav, or do anything.
s._requestOraclePrice(s.endTime);
s._payOracleFees(feeAmount);
return;
}
uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime);
// Update nav of contract.
int navNew = s._computeNav(latestPrice, latestTime);
// Update the balances of the contract.
s._updateBalances(navNew);
// Make sure contract has not moved into default.
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
s.state = TDS.State.Defaulted;
s.defaultPenaltyAmount = potentialPenaltyAmount;
s.endTime = latestTime; // Change end time to moment when default occurred.
emit Default(s.fixedParameters.symbol, latestTime, s.nav);
s._requestOraclePrice(latestTime);
}
s._payOracleFees(feeAmount);
}
function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) {
s._remarginInternal();
// Verify that remargining didn't push the contract into expiry or default.
require(s.state == TDS.State.Live);
int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase);
if (purchasedNav < 0) {
purchasedNav = 0;
}
// Ensures that requiredNav >= navSent.
refund = navSent.sub(_safeUintCast(purchasedNav));
s.longBalance = s.longBalance.add(purchasedNav);
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
thisErc20Token.mint(msg.sender, tokensToPurchase);
emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase);
s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
// Make sure this still satisfies the margin requirement.
require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState));
}
function _depositInternal(TDS.Storage storage s, uint value) internal {
// Make sure that we are in a "depositable" state.
require(s.state == TDS.State.Live);
s.shortBalance = s.shortBalance.add(_safeIntCast(value));
emit Deposited(s.fixedParameters.symbol, value);
}
function _settleInternal(TDS.Storage storage s) internal {
TDS.State startingState = s.state;
require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired
|| startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency);
s._settleVerifiedPrice();
if (startingState == TDS.State.Disputed) {
int depositValue = _safeIntCast(s.disputeInfo.deposit);
if (s.nav != s.disputeInfo.disputedNav) {
s.shortBalance = s.shortBalance.add(depositValue);
} else {
s.longBalance = s.longBalance.add(depositValue);
}
}
}
// Deducts the fees from the margin account.
function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) {
feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime);
s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount));
// If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the
// contract.
}
// Pays out the fees to the Oracle.
function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal {
if (feeAmount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
s.externalAddresses.store.payOracleFees.value(feeAmount)();
} else {
require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount));
s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency));
}
}
function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime)
internal
view
returns (uint feeAmount)
{
// The profit from corruption is set as the max(longBalance, shortBalance).
int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance;
uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc));
// Ensure the fee returned can actually be paid by the short margin account.
uint shortBalance = _safeUintCast(s.shortBalance);
return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount;
}
function _computeNewTokenState(TDS.Storage storage s,
TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime)
internal
view
returns (TDS.TokenState memory newTokenState)
{
int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn(
beginningTokenState.underlyingPrice, latestUnderlyingPrice);
int tokenReturn = underlyingReturn.sub(
_safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time))));
int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR);
// In the compound case, don't allow the token price to go below 0.
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) {
tokenMultiplier = 0;
}
int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier);
newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime);
}
function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState)
internal
view
returns (bool doesSatisfyRequirement)
{
return s._getRequiredMargin(tokenState) <= balance;
}
function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal {
uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime);
if (expectedTime == 0) {
// The Oracle price is already available, settle the contract right away.
s._settleInternal();
}
}
function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) {
(latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product);
require(latestTime != 0);
}
function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) {
navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime);
} else {
assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear);
navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime);
}
}
function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
s.referenceTokenState = s.currentTokenState;
s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) {
// Only update the time - don't update the prices becuase all price changes are relative to the initial price.
s.referenceTokenState.time = s.currentTokenState.time;
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) {
// We're updating `last` based on what the Oracle has told us.
assert(s.endTime == recomputeTime);
s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime);
navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply());
emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice);
}
// Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all
// of the settlement logic including assessing penalties and then moves the state to `Settled`.
function _settleWithPrice(TDS.Storage storage s, int price) internal {
// Remargin at whatever price we're using (verified or unverified).
s._updateBalances(s._recomputeNav(price, s.endTime));
bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState);
if (inDefault) {
int expectedDefaultPenalty = s._getDefaultPenalty();
int penalty = (s.shortBalance < expectedDefaultPenalty) ?
s.shortBalance :
expectedDefaultPenalty;
s.shortBalance = s.shortBalance.sub(penalty);
s.longBalance = s.longBalance.add(penalty);
}
s.state = TDS.State.Settled;
emit Settled(s.fixedParameters.symbol, s.endTime, s.nav);
}
function _updateBalances(TDS.Storage storage s, int navNew) internal {
// Compute difference -- Add the difference to owner and subtract
// from counterparty. Then update nav state variable.
int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance);
s.nav = navNew;
s.longBalance = s.longBalance.add(longDiff);
s.shortBalance = s.shortBalance.sub(longDiff);
}
function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return s.defaultPenaltyAmount;
}
function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) {
return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty);
}
function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState)
internal
view
returns (int requiredMargin)
{
int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage());
int effectiveNotional;
if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) {
int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude);
effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR);
} else {
int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply());
effectiveNotional = currentNav.mul(leverageMagnitude);
}
// Take the absolute value of the notional since a negative notional has similar risk properties to a positive
// notional of the same size, and, therefore, requires the same margin.
requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove);
}
function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) {
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
// Refund is any amount of ETH that was sent that was above the amount that was expected.
// Note: SafeMath will force a revert if msg.value < expectedMargin.
return msg.value.sub(expectedMargin);
} else {
// If we expect an ERC20 token, no ETH should be sent.
require(msg.value == 0);
_pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin);
// There is never a refund in the ERC20 case since we use the argument to determine how much to "pull".
return 0;
}
}
function _sendMargin(TDS.Storage storage s, uint amount) internal {
// There's no point in attempting a send if there's nothing to send.
if (amount == 0) {
return;
}
if (address(s.externalAddresses.marginCurrency) == address(0x0)) {
msg.sender.transfer(amount);
} else {
require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount));
}
}
function _settleAgreedPrice(TDS.Storage storage s) internal {
int agreedPrice = s.currentTokenState.underlyingPrice;
s._settleWithPrice(agreedPrice);
}
function _settleVerifiedPrice(TDS.Storage storage s) internal {
int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime);
s._settleWithPrice(oraclePrice);
}
function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private {
// If nothing is being pulled, there's no point in calling a transfer.
if (amountToPull > 0) {
require(erc20.transferFrom(msg.sender, address(this), amountToPull));
}
}
// Gets the change in balance for the long side.
// Note: there's a function for this because signage is tricky here, and it must be done the same everywhere.
function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) {
int newLongBalance = navNew;
// Long balance cannot go below zero.
if (newLongBalance < 0) {
newLongBalance = 0;
}
longDiff = newLongBalance.sub(longBalance);
// Cannot pull more margin from the short than is available.
if (longDiff > shortBalance) {
longDiff = shortBalance;
}
}
function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) {
int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice);
navNew = navPreDivision.div(INT_FP_SCALING_FACTOR);
// The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens
// cannot be purchased or backed with less than their true value.
if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) {
navNew = navNew.add(1);
}
}
function _totalSupply() private view returns (uint totalSupply) {
ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this));
return thisErc20Token.totalSupply();
}
function _takePercentage(uint value, uint percentage) private pure returns (uint result) {
return value.mul(percentage).div(UINT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, uint percentage) private pure returns (int result) {
return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR);
}
function _takePercentage(int value, int percentage) private pure returns (int result) {
return value.mul(percentage).div(INT_FP_SCALING_FACTOR);
}
function _absoluteValue(int value) private pure returns (int result) {
return value < 0 ? value.mul(-1) : value;
}
function _safeIntCast(uint value) private pure returns (int result) {
require(value <= INT_MAX);
return int(value);
}
function _safeUintCast(int value) private pure returns (uint result) {
require(value >= 0);
return uint(value);
}
// Note that we can't have the symbol parameter be `indexed` due to:
// TypeError: Indexed reference types cannot yet be used with ABIEncoderV2.
// An event emitted when the NAV of the contract changes.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
// An event emitted when the contract enters the Default state on a remargin.
event Default(string symbol, uint defaultTime, int defaultNav);
// An event emitted when the contract settles.
event Settled(string symbol, uint settleTime, int finalNav);
// An event emitted when the contract expires.
event Expired(string symbol, uint expiryTime);
// An event emitted when the contract's NAV is disputed by the sponsor.
event Disputed(string symbol, uint timeDisputed, int navDisputed);
// An event emitted when the contract enters emergency shutdown.
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
// An event emitted when tokens are created.
event TokensCreated(string symbol, uint numTokensCreated);
// An event emitted when tokens are redeemed.
event TokensRedeemed(string symbol, uint numTokensRedeemed);
// An event emitted when margin currency is deposited.
event Deposited(string symbol, uint amount);
// An event emitted when margin currency is withdrawn.
event Withdrawal(string symbol, uint amount);
}
// TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality.
contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 {
using TokenizedDerivativeUtils for TDS.Storage;
// Note: these variables are to give ERC20 consumers information about the token.
string public name;
string public symbol;
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
TDS.Storage public derivativeStorage;
constructor(
TokenizedDerivativeParams.ConstructorParams memory params,
string memory _name,
string memory _symbol
) public {
// Set token properties.
name = _name;
symbol = _symbol;
// Initialize the contract.
derivativeStorage._initialize(params, _symbol);
}
// Creates tokens with sent margin and returns additional margin.
function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._createTokens(marginForPurchase, tokensToPurchase);
}
// Creates tokens with sent margin and deposits additional margin in short account.
function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable {
derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase);
}
// Redeems tokens for margin currency.
function redeemTokens(uint tokensToRedeem) external {
derivativeStorage._redeemTokens(tokensToRedeem);
}
// Triggers a price dispute for the most recent remargin time.
function dispute(uint depositMargin) external payable {
derivativeStorage._dispute(depositMargin);
}
// Withdraws `amount` from short margin account.
function withdraw(uint amount) external {
derivativeStorage._withdraw(amount);
}
// Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and
// short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements.
function remargin() external {
derivativeStorage._remargin();
}
// Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on
// contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long
// account.
function acceptPriceAndSettle() external {
derivativeStorage._acceptPriceAndSettle();
}
// Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no
// Delegate AP.
function setApDelegate(address apDelegate) external {
derivativeStorage._setApDelegate(apDelegate);
}
// Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time.
function emergencyShutdown() external {
derivativeStorage._emergencyShutdown();
}
// Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price.
function calcNAV() external view returns (int navNew) {
return derivativeStorage._calcNAV();
}
// Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed
// price.
function calcTokenValue() external view returns (int newTokenValue) {
return derivativeStorage._calcTokenValue();
}
// Returns the expected balance of the short margin account using the latest available Price Feed price.
function calcShortMarginBalance() external view returns (int newShortMarginBalance) {
return derivativeStorage._calcShortMarginBalance();
}
// Returns the expected short margin in excess of the margin requirement using the latest available Price Feed
// price. Value will be negative if the short margin is expected to be below the margin requirement.
function calcExcessMargin() external view returns (int excessMargin) {
return derivativeStorage._calcExcessMargin();
}
// Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the
// latest available Price Feed price.
function getCurrentRequiredMargin() external view returns (int requiredMargin) {
return derivativeStorage._getCurrentRequiredMargin();
}
// Returns whether the contract can be settled, i.e., is it valid to call settle() now.
function canBeSettled() external view returns (bool canContractBeSettled) {
return derivativeStorage._canBeSettled();
}
// Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if
// the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled.
// Reverts if no Oracle price is available but an Oracle price is required.
function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) {
return derivativeStorage._getUpdatedUnderlyingPrice();
}
// When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract
// into the `Settled` state.
function settle() external {
derivativeStorage._settle();
}
// Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call)
// to the short account.
function deposit(uint amountToDeposit) external payable {
derivativeStorage._deposit(amountToDeposit);
}
// Allows the sponsor to withdraw any ERC20 balance that is not the margin token.
function withdrawUnexpectedErc20(address erc20Address, uint amount) external {
derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount);
}
// ExpandedIERC20 methods.
modifier onlyThis {
require(msg.sender == address(this));
_;
}
// Only allow calls from this contract or its libraries to burn tokens.
function burn(uint value) external onlyThis {
// Only allow calls from this contract or its libraries to burn tokens.
_burn(msg.sender, value);
}
// Only allow calls from this contract or its libraries to mint tokens.
function mint(address to, uint256 value) external onlyThis {
_mint(to, value);
}
// These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events
// here as well.
event NavUpdated(string symbol, int newNav, int newTokenPrice);
event Default(string symbol, uint defaultTime, int defaultNav);
event Settled(string symbol, uint settleTime, int finalNav);
event Expired(string symbol, uint expiryTime);
event Disputed(string symbol, uint timeDisputed, int navDisputed);
event EmergencyShutdownTransition(string symbol, uint shutdownTime);
event TokensCreated(string symbol, uint numTokensCreated);
event TokensRedeemed(string symbol, uint numTokensRedeemed);
event Deposited(string symbol, uint amount);
event Withdrawal(string symbol, uint amount);
}
contract TokenizedDerivativeCreator is ContractCreator, Testable {
struct Params {
uint defaultPenalty; // Percentage of mergin requirement * 10^18
uint supportedMove; // Expected percentage move in the underlying that the long is protected against.
bytes32 product;
uint fixedYearlyFee; // Percentage of nav * 10^18
uint disputeDeposit; // Percentage of mergin requirement * 10^18
address returnCalculator;
uint startingTokenPrice;
uint expiry;
address marginCurrency;
uint withdrawLimit; // Percentage of shortBalance * 10^18
TokenizedDerivativeParams.ReturnType returnType;
uint startingUnderlyingPrice;
string name;
string symbol;
}
AddressWhitelist public sponsorWhitelist;
AddressWhitelist public returnCalculatorWhitelist;
AddressWhitelist public marginCurrencyWhitelist;
constructor(
address registryAddress,
address _oracleAddress,
address _storeAddress,
address _priceFeedAddress,
address _sponsorWhitelist,
address _returnCalculatorWhitelist,
address _marginCurrencyWhitelist,
bool _isTest
)
public
ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress)
Testable(_isTest)
{
sponsorWhitelist = AddressWhitelist(_sponsorWhitelist);
returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist);
marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist);
}
function createTokenizedDerivative(Params memory params)
public
returns (address derivativeAddress)
{
TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol);
address[] memory parties = new address[](1);
parties[0] = msg.sender;
_registerContract(parties, address(derivative));
return address(derivative);
}
// Converts createTokenizedDerivative params to TokenizedDerivative constructor params.
function _convertParams(Params memory params)
private
view
returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams)
{
// Copy and verify externally provided variables.
require(sponsorWhitelist.isOnWhitelist(msg.sender));
constructorParams.sponsor = msg.sender;
require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator));
constructorParams.returnCalculator = params.returnCalculator;
require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency));
constructorParams.marginCurrency = params.marginCurrency;
constructorParams.defaultPenalty = params.defaultPenalty;
constructorParams.supportedMove = params.supportedMove;
constructorParams.product = params.product;
constructorParams.fixedYearlyFee = params.fixedYearlyFee;
constructorParams.disputeDeposit = params.disputeDeposit;
constructorParams.startingTokenPrice = params.startingTokenPrice;
constructorParams.expiry = params.expiry;
constructorParams.withdrawLimit = params.withdrawLimit;
constructorParams.returnType = params.returnType;
constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice;
// Copy internal variables.
constructorParams.priceFeed = priceFeedAddress;
constructorParams.oracle = oracleAddress;
constructorParams.store = storeAddress;
constructorParams.admin = oracleAddress;
constructorParams.creationTime = getCurrentTime();
}
} | Computes the return between oldPrice and newPrice. Gets the effective leverage for the return calculator. Note: if this parameter doesn't exist for this calculator, this method should return 1. | interface ReturnCalculatorInterface {
function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn);
function leverage() external view returns (int _leverage);
}
| 972,235 |
// Sources flattened with hardhat v2.6.7 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// 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);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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();
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/security/[email protected]
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;
}
}
// File contracts/PaymentSplitter.sol
//
//ÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòùÔûæÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔÇâÔÇâÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔòù
//ÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûêÔûêÔòöÔòØÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòÉÔòØÔÇâÔÇâÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòÉÔòØÔòÜÔòÉÔòÉÔûêÔûêÔòöÔòÉÔòÉÔòØ
//ÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔòÉÔòØÔûæÔòÜÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔÇâÔÇâÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòØÔûæÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔûêÔûêÔòùÔûæÔûæÔòÜÔòÉÔòÉÔòÉÔûêÔûêÔòùÔÇâÔÇâÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔûæÔûæÔûæÔûæÔòÜÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔÇâÔÇâÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûæÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòØÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔÇâÔÇâÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔòÜÔòÉÔòØÔûæÔûæÔûæ
//
pragma solidity ^0.8.0;
/********************Begin of Payment Splitter *********************************/
/**
* @dev this section contains the methods used
* to split payment between all collaborators of this project
*/
contract PaymentSplitter is Ownable{
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
bool private initialized = false;
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
require(msg.sender == account,"Not authorized");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, "Account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
// payable(account).send(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal {
require(
account != address(0),
"Account is the zero address"
);
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(
_shares[account] == 0,
"Account already has shares"
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
/**
* @dev Return all payees
*/
function getPayees() public view returns (address[] memory) {
return _payees;
}
/**
* @dev Set up all holders shares
* @param payees wallets of holders.
* @param shares_ shares of each holder.
*/
function initializePaymentSplitter(
address[] memory payees,
uint256[] memory shares_
) public onlyOwner {
require(!initialized, "Payment Split Already Initialized!");
require(
payees.length == shares_.length,
"Payees and shares length mismatch"
);
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
initialized = true;
}
}
/********************End of Payment Splitter *********************************/
// File contracts/DinoPunks.sol
//
//ÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòùÔûæÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûæÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔÇâÔÇâÔûêÔûêÔûêÔòùÔûæÔûæÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔûêÔòù
//ÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòöÔòÉÔòÉÔûêÔûêÔòùÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûêÔûêÔòöÔòØÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòÉÔòØÔÇâÔÇâÔûêÔûêÔûêÔûêÔòùÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòÉÔòØÔòÜÔòÉÔòÉÔûêÔûêÔòöÔòÉÔòÉÔòØ
//ÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔòÉÔòØÔûæÔòÜÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔÇâÔÇâÔûêÔûêÔòöÔûêÔûêÔòùÔûêÔûêÔòæÔûêÔûêÔûêÔûêÔûêÔòùÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòÉÔòØÔûæÔûêÔûêÔòæÔûæÔûæÔûæÔûêÔûêÔòæÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔûêÔûêÔòùÔûæÔûæÔòÜÔòÉÔòÉÔòÉÔûêÔûêÔòùÔÇâÔÇâÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔòæÔûêÔûêÔòöÔòÉÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔòÜÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔûæÔûæÔûæÔûæÔòÜÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔòùÔûêÔûêÔûêÔûêÔûêÔûêÔòöÔòØÔÇâÔÇâÔûêÔûêÔòæÔûæÔòÜÔûêÔûêÔûêÔòæÔûêÔûêÔòæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûêÔûêÔòæÔûæÔûæÔûæ
//ÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûæÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòØÔòÜÔòÉÔòÉÔòÉÔòÉÔòÉÔòØÔûæÔÇâÔÇâÔòÜÔòÉÔòØÔûæÔûæÔòÜÔòÉÔòÉÔòØÔòÜÔòÉÔòØÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔûæÔòÜÔòÉÔòØÔûæÔûæÔûæ
//
pragma solidity >=0.8.0;
/**
* @dev contract module which defines Dino Punks NFT Collection
* and all the interactions it uses
*/
contract DinoPunks is ERC721Enumerable, Ownable, PaymentSplitter, ReentrancyGuard {
using Strings for uint256;
//@dev Attributes for NFT configuration
string internal baseURI;
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 8888;
uint256 public maxMintAmount = 5;
mapping(address => uint256) public whitelist;
mapping(uint256 => string) private _tokenURIs;
mapping(address => bool) presaleAddress;
uint256[] mintedEditions;
bool public presale;
bool public paused = true;
bool public revealed;
// @dev inner attributes of the contract
/**
* @dev Create an instance of Dino Punks contract
* @param _initBaseURI Base URI for NFT metadata.
*/
constructor(
string memory _initBaseURI
// address[] memory _payees,
// uint256[] memory _amount,
) ERC721("DinoPunks", "DinoPunks"){
setBaseURI(_initBaseURI);
// initializePaymentSplitter(_payees, _amount);
}
/**
* @dev get base URI for NFT metadata
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @dev set new max supply for the smart contract
* @param _newMaxSupply new max supply
*/
function setNewMaxSupply(uint256 _newMaxSupply) public onlyOwner {
maxSupply = _newMaxSupply;
}
/**
*
* @dev Mint edition to a wallet
* @param _to wallet receiving the edition(s).
* @param _mintAmount number of editions to mint.
*/
function mint(address _to, uint256 _mintAmount) public payable nonReentrant {
require(paused == false,"Minting is paused");
require(_mintAmount <= maxMintAmount, "Cannot exceed max mint amount");
if(presale == true)
require(presaleAddress[msg.sender] == true,"Address not whitelisted for pre-sale minting");
uint256 supply = totalSupply();
require(
supply + _mintAmount <= maxSupply,
"Not enough mintable editions !"
);
require(
msg.value >= cost * _mintAmount,
"Insufficient transaction amount."
);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
/**
* @dev whitelistMint edition to a wallet
* @param _to wallet receiving the edition(s).
* @param _mintAmount number of editions to mint.
*/
function freeMint(address _to, uint256 _mintAmount) public nonReentrant{
uint256 supply = totalSupply();
require(
_mintAmount <= whitelist[msg.sender],
"Amount exceeds allowance"
);
require(
supply + _mintAmount <= maxSupply,
"Not enough mintable editions !"
);
whitelist[msg.sender] -= _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
/**
* @dev get balance contained in the smart contract
*/
function getBalance() public view onlyOwner returns (uint256) {
return address(this).balance;
}
/**
* @dev change cost of NFT
* @param _newCost new cost of each edition
*/
function setCost(uint256 _newCost) public onlyOwner {
require(_newCost > 0, "New cost can not be 0");
cost = _newCost;
}
/**
* @dev restrict max mintable amount of edition at a time
* @param _newmaxMintAmount new max mintable amount
*/
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
require(_newmaxMintAmount > 0, "New mint amount cannot be 0");
maxMintAmount = _newmaxMintAmount;
}
/**
* @dev change metadata uri
* @param _newBaseURI new URI for metadata
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/**
* @dev Disable minting process
*/
function pause() public onlyOwner {
paused = !paused;
}
/**
* @dev Activate presaleAddress
*/
function activatePresale() public onlyOwner {
presale = !presale;
}
/**
* @dev Activate presaleAddress
*/
function presaleMembers(address[] memory _presaleAddress) public onlyOwner {
for(uint i = 0; i< _presaleAddress.length; i++)
presaleAddress[_presaleAddress[i]] = true;
}
/**
* @dev Add user to white list
* @param _user Users wallet to whitelist
*/
function whitelistUserBatch(
address[] memory _user,
uint256[] memory _amount
) public onlyOwner {
require(_user.length == _amount.length);
for (uint256 i = 0; i < _user.length; i++)
whitelist[_user[i]] = _amount[i];
}
/**
* @dev Reveal metadata
* @param _newURI new metadata URI
*/
function reveal(string memory _newURI) public onlyOwner {
setBaseURI(_newURI);
revealed = true;
}
/**
* @dev Get token URI
* @param tokenId ID of the token to retrieve
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"URI query for nonexistent token"
);
if(revealed == false)
return baseURI;
else {
if (bytes(_tokenURIs[tokenId]).length == 0) {
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
} else return _tokenURIs[tokenId];
}
}
function burn(uint256[] memory _tokenIds) public onlyOwner {
for( uint256 i = 0; i < _tokenIds.length; i++)
_burn(_tokenIds[i]);
}
} | Get token URI tokenId ID of the token to retrieve/ | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"URI query for nonexistent token"
);
if(revealed == false)
return baseURI;
else {
if (bytes(_tokenURIs[tokenId]).length == 0) {
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
} else return _tokenURIs[tokenId];
}
}
| 6,989,128 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8;
import "./AdminControlled.sol";
import "./INearBridge.sol";
import "./NearDecoder.sol";
// used to sign messages of the validators that approve the block, and thus to also check validity of the signature in the submitted NEAR block header
import "./Ed25519.sol";
// Near Light Client on Ethereum
contract NearBridge is INearBridge, AdminControlled {
using Borsh for Borsh.Data;
using NearDecoder for Borsh.Data;
// Assumed to be even and to not exceed 256.
uint constant MAX_BLOCK_PRODUCERS = 100;
struct Epoch {
bytes32 epochId;
uint numBPs;
bytes32[MAX_BLOCK_PRODUCERS] keys;
bytes32[MAX_BLOCK_PRODUCERS / 2] packedStakes;
uint256 stakeThreshold;
}
uint256 public lockEthAmount;
// lockDuration and replaceDuration shouldn't be extremely big, so adding them to an uint64 timestamp should not overflow uint256.
uint256 public lockDuration;
// replaceDuration is in nanoseconds, because it is a difference between NEAR timestamps.
uint256 public replaceDuration;
Ed25519 immutable edwards;
// End of challenge period. If zero, untrusted* fields and lastSubmitter are not meaningful.
uint256 public lastValidAt;
uint64 curHeight;
// The most recently added block. May still be in its challenge period, so should not be trusted.
uint64 untrustedHeight;
// Address of the account which submitted the last block.
address lastSubmitter;
// Whether the contract was initialized.
bool public initialized;
bool untrustedNextEpoch;
bytes32 untrustedHash;
bytes32 untrustedMerkleRoot;
bytes32 untrustedNextHash;
uint256 untrustedTimestamp;
uint256 untrustedSignatureSet;
NearDecoder.Signature[MAX_BLOCK_PRODUCERS] untrustedSignatures;
Epoch[3] epochs;
uint256 curEpoch;
mapping(uint64 => bytes32) blockHashes_;
mapping(uint64 => bytes32) blockMerkleRoots_;
// tracks users bond deposit amounts
mapping(address => uint256) public override balanceOf;
// initialize NEAR bridge
constructor(
Ed25519 ed,
uint256 lockEthAmount_,
uint256 lockDuration_,
uint256 replaceDuration_,
address admin_,
uint256 pausedFlags_
) AdminControlled(admin_, pausedFlags_) {
require(replaceDuration_ > lockDuration_ * 1000000000);
edwards = ed;
lockEthAmount = lockEthAmount_;
lockDuration = lockDuration_;
replaceDuration = replaceDuration_;
}
uint constant UNPAUSE_ALL = 0;
uint constant PAUSED_DEPOSIT = 1;
uint constant PAUSED_WITHDRAW = 2;
uint constant PAUSED_ADD_BLOCK = 4;
uint constant PAUSED_CHALLENGE = 8;
uint constant PAUSED_VERIFY = 16;
// deposits bond amount for a user submitting a NEAR header if no bond deposit exists already
function deposit() public payable override pausable(PAUSED_DEPOSIT) {
require(msg.value == lockEthAmount && balanceOf[msg.sender] == 0);
// set balance of user to ETH bond amount if no balance previously
balanceOf[msg.sender] = msg.value;
}
// allow bond amount to be withdrawn once user's submitted block header has passed challenge period
function withdraw() public override pausable(PAUSED_WITHDRAW) {
require(msg.sender != lastSubmitter || block.timestamp >= lastValidAt);
uint amount = balanceOf[msg.sender];
require(amount != 0);
balanceOf[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
// NEAR uses fraud proof to verify that signature of submitted block header is valid, anyone can challenge it in the 4 hour challenge period
function challenge(address payable receiver, uint signatureIndex) external override pausable(PAUSED_CHALLENGE) {
require(block.timestamp < lastValidAt, "No block can be challenged at this time");
require(!checkBlockProducerSignatureInHead(signatureIndex), "Can't challenge valid signature");
// penalizes user who submitted the NEAR header by the bond amount because the signature failed the challenge
balanceOf[lastSubmitter] = balanceOf[lastSubmitter] - lockEthAmount;
// reset last valid block
lastValidAt = 0;
// challenger receives half of the bond amount, other half gets burned
receiver.call{value: lockEthAmount / 2}("");
}
// used to verify whether signature is valid or invalid by challenge
function checkBlockProducerSignatureInHead(uint signatureIndex) public view override returns (bool) {
// Shifting by a number >= 256 returns zero.
require((untrustedSignatureSet & (1 << signatureIndex)) != 0, "No such signature");
unchecked {
Epoch storage untrustedEpoch = epochs[untrustedNextEpoch ? (curEpoch + 1) % 3 : curEpoch];
NearDecoder.Signature storage signature = untrustedSignatures[signatureIndex];
bytes memory message = abi.encodePacked(
uint8(0),
untrustedNextHash,
Utils.swapBytes8(untrustedHeight + 2),
bytes23(0)
);
(bytes32 arg1, bytes9 arg2) = abi.decode(message, (bytes32, bytes9));
// use Ed25519 contract to check if the signature is invalid
return edwards.check(untrustedEpoch.keys[signatureIndex], signature.r, signature.s, arg1, arg2);
}
}
// The first part of initialization -- setting the validators of the current epoch.
function initWithValidators(bytes memory data) public override onlyAdmin {
require(!initialized && epochs[0].numBPs == 0, "Wrong initialization stage");
Borsh.Data memory borsh = Borsh.from(data);
NearDecoder.BlockProducer[] memory initialValidators = borsh.decodeBlockProducers();
borsh.done();
setBlockProducers(initialValidators, epochs[0]);
}
// The second part of the initialization -- setting the current head.
function initWithBlock(bytes memory data) public override onlyAdmin {
require(!initialized && epochs[0].numBPs != 0, "Wrong initialization stage");
initialized = true;
Borsh.Data memory borsh = Borsh.from(data);
NearDecoder.LightClientBlock memory nearBlock = borsh.decodeLightClientBlock();
borsh.done();
require(nearBlock.next_bps.some, "Initialization block must contain next_bps");
curHeight = nearBlock.inner_lite.height;
epochs[0].epochId = nearBlock.inner_lite.epoch_id;
epochs[1].epochId = nearBlock.inner_lite.next_epoch_id;
blockHashes_[nearBlock.inner_lite.height] = nearBlock.hash;
blockMerkleRoots_[nearBlock.inner_lite.height] = nearBlock.inner_lite.block_merkle_root;
setBlockProducers(nearBlock.next_bps.blockProducers, epochs[1]);
}
struct BridgeState {
uint currentHeight; // Height of the current confirmed block
// If there is currently no unconfirmed block, the last three fields are zero.
uint nextTimestamp; // Timestamp of the current unconfirmed block
uint nextValidAt; // Timestamp when the current unconfirmed block will be confirmed
uint numBlockProducers; // Number of block producers for the current unconfirmed block
}
function bridgeState() public view returns (BridgeState memory res) {
if (block.timestamp < lastValidAt) {
// there exists an untrustedNextEpoch still within a challenge period
res.currentHeight = curHeight;
res.nextTimestamp = untrustedTimestamp;
res.nextValidAt = lastValidAt;
unchecked {
res.numBlockProducers = epochs[untrustedNextEpoch ? (curEpoch + 1) % 3 : curEpoch].numBPs;
}
} else {
res.currentHeight = lastValidAt == 0 ? curHeight : untrustedHeight;
}
}
// user can submit next block to update light client if bond deposit checks pass
function addLightClientBlock(bytes memory data) public override pausable(PAUSED_ADD_BLOCK) {
require(initialized, "Contract is not initialized");
// user needs to have enough balance in the contract for the bond
require(balanceOf[msg.sender] >= lockEthAmount, "Balance is not enough");
Borsh.Data memory borsh = Borsh.from(data);
NearDecoder.LightClientBlock memory nearBlock = borsh.decodeLightClientBlock();
borsh.done();
unchecked {
// Commit the previous block, or make sure that it is OK to replace it.
if (block.timestamp < lastValidAt) {
require(
nearBlock.inner_lite.timestamp >= untrustedTimestamp + replaceDuration,
"Can only replace with a sufficiently newer block"
);
} else if (lastValidAt != 0) {
curHeight = untrustedHeight;
if (untrustedNextEpoch) {
curEpoch = (curEpoch + 1) % 3;
}
lastValidAt = 0;
blockHashes_[curHeight] = untrustedHash;
blockMerkleRoots_[curHeight] = untrustedMerkleRoot;
}
// Check that the new block's height is greater than the current one's.
require(nearBlock.inner_lite.height > curHeight, "New block must have higher height");
// Check that the new block is from the same epoch as the current one, or from the next one.
bool fromNextEpoch;
if (nearBlock.inner_lite.epoch_id == epochs[curEpoch].epochId) {
fromNextEpoch = false;
} else if (nearBlock.inner_lite.epoch_id == epochs[(curEpoch + 1) % 3].epochId) {
fromNextEpoch = true;
} else {
revert("Epoch id of the block is not valid");
}
// Check that the new block is signed by more than 2/3 of the validators.
Epoch storage thisEpoch = epochs[fromNextEpoch ? (curEpoch + 1) % 3 : curEpoch];
// Last block in the epoch might contain extra approvals that light client can ignore.
require(nearBlock.approvals_after_next.length >= thisEpoch.numBPs, "Approval list is too short");
// The sum of uint128 values cannot overflow.
uint256 votedFor = 0;
for ((uint i, uint cnt) = (0, thisEpoch.numBPs); i != cnt; ++i) {
bytes32 stakes = thisEpoch.packedStakes[i >> 1];
if (nearBlock.approvals_after_next[i].some) {
votedFor += uint128(bytes16(stakes));
}
if (++i == cnt) {
break;
}
if (nearBlock.approvals_after_next[i].some) {
votedFor += uint128(uint256(stakes));
}
}
require(votedFor > thisEpoch.stakeThreshold, "Too few approvals");
// If the block is from the next epoch, make sure that next_bps is supplied and has a correct hash.
if (fromNextEpoch) {
require(nearBlock.next_bps.some, "Next next_bps should not be None");
require(
nearBlock.next_bps.hash == nearBlock.inner_lite.next_bp_hash,
"Hash of block producers does not match"
);
}
untrustedHeight = nearBlock.inner_lite.height;
untrustedTimestamp = nearBlock.inner_lite.timestamp;
untrustedHash = nearBlock.hash;
untrustedMerkleRoot = nearBlock.inner_lite.block_merkle_root;
untrustedNextHash = nearBlock.next_hash;
// gather new untrusted signature set from submitted block
uint256 signatureSet = 0;
for ((uint i, uint cnt) = (0, thisEpoch.numBPs); i < cnt; i++) {
NearDecoder.OptionalSignature memory approval = nearBlock.approvals_after_next[i];
if (approval.some) {
signatureSet |= 1 << i;
untrustedSignatures[i] = approval.signature;
}
}
untrustedSignatureSet = signatureSet;
untrustedNextEpoch = fromNextEpoch;
if (fromNextEpoch) {
Epoch storage nextEpoch = epochs[(curEpoch + 2) % 3];
nextEpoch.epochId = nearBlock.inner_lite.next_epoch_id;
setBlockProducers(nearBlock.next_bps.blockProducers, nextEpoch);
}
lastSubmitter = msg.sender;
// set when next challenge period ends
lastValidAt = block.timestamp + lockDuration;
}
}
// used to set validators of a given epoch while checking that the number of validators does not exceed the limit
function setBlockProducers(NearDecoder.BlockProducer[] memory src, Epoch storage epoch) internal {
uint cnt = src.length;
require(
cnt <= MAX_BLOCK_PRODUCERS,
"It is not expected having that many block producers for the provided block"
);
epoch.numBPs = cnt;
unchecked {
for (uint i = 0; i < cnt; i++) {
epoch.keys[i] = src[i].publicKey.k;
}
uint256 totalStake = 0; // Sum of uint128, can't be too big.
for (uint i = 0; i != cnt; ++i) {
uint128 stake1 = src[i].stake;
totalStake += stake1;
if (++i == cnt) {
epoch.packedStakes[i >> 1] = bytes32(bytes16(stake1));
break;
}
uint128 stake2 = src[i].stake;
totalStake += stake2;
epoch.packedStakes[i >> 1] = bytes32(uint256(bytes32(bytes16(stake1))) + stake2);
}
// stake cannot exceed 2/3 validators threshhold
epoch.stakeThreshold = (totalStake * 2) / 3;
}
}
// get all block hashes at a given block height
function blockHashes(uint64 height) public view override pausable(PAUSED_VERIFY) returns (bytes32 res) {
res = blockHashes_[height];
if (res == 0 && block.timestamp >= lastValidAt && lastValidAt != 0 && height == untrustedHeight) {
res = untrustedHash;
}
}
// get all block merkle roots at a given block height
function blockMerkleRoots(uint64 height) public view override pausable(PAUSED_VERIFY) returns (bytes32 res) {
res = blockMerkleRoots_[height];
if (res == 0 && block.timestamp >= lastValidAt && lastValidAt != 0 && height == untrustedHeight) {
res = untrustedMerkleRoot;
}
}
}
| used to verify whether signature is valid or invalid by challenge Shifting by a number >= 256 returns zero. use Ed25519 contract to check if the signature is invalid | function checkBlockProducerSignatureInHead(uint signatureIndex) public view override returns (bool) {
require((untrustedSignatureSet & (1 << signatureIndex)) != 0, "No such signature");
unchecked {
Epoch storage untrustedEpoch = epochs[untrustedNextEpoch ? (curEpoch + 1) % 3 : curEpoch];
NearDecoder.Signature storage signature = untrustedSignatures[signatureIndex];
bytes memory message = abi.encodePacked(
uint8(0),
untrustedNextHash,
Utils.swapBytes8(untrustedHeight + 2),
bytes23(0)
);
(bytes32 arg1, bytes9 arg2) = abi.decode(message, (bytes32, bytes9));
return edwards.check(untrustedEpoch.keys[signatureIndex], signature.r, signature.s, arg1, arg2);
}
}
| 12,793,767 |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY344() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF995(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER795(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE796(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE408(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM856(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function DECIMALS615() external view returns (uint); //inject NONSTANDARD NAMING
event TRANSFER370(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL858(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD697(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB109(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB109(a, b, "SafeMath: subtraction overflow");
}
function SUB109(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 MUL960(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV581(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV581(a, b, "SafeMath: division by zero");
}
function DIV581(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD970(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD970(a, b, "SafeMath: modulo by zero");
}
function MOD970(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT908(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE655(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE370(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER212(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFER795.selector, to, value));
}
function SAFETRANSFERFROM22(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFERFROM856.selector, from, to, value));
}
function SAFEAPPROVE493(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE796(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.APPROVE408.selector, spender, value));
}
function CALLOPTIONALRETURN170(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT908(), "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");
}
}
}
interface Controller {
function VAULTS291(address) external view returns (address); //inject NONSTANDARD NAMING
}
interface Balancer {
function JOINPOOL849(uint,uint[] calldata) external; //inject NONSTANDARD NAMING
function EXITPOOL804(uint,uint[] calldata) external; //inject NONSTANDARD NAMING
}
interface MStable {
function MINT666(address, uint) external; //inject NONSTANDARD NAMING
function REDEEM500(address, uint) external; //inject NONSTANDARD NAMING
}
contract StrategyBalancerMTA {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want295 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); //inject NONSTANDARD NAMING
address constant public musd674 = address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); //inject NONSTANDARD NAMING
address constant public balancer837 = address(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); //inject NONSTANDARD NAMING
address public governance;
address public controller;
bool public breaker = false;
// Supply tracks the number of `want` that we have lent out of other distro's
uint public supply = 0;
constructor(address _controller) public {
governance = msg.sender;
controller = _controller;
}
function SETBREAKER384(bool _breaker) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
breaker = _breaker;
}
function DEPOSIT98() external { //inject NONSTANDARD NAMING
require(breaker == false, "!breaker");
uint _balance = IERC20(want295).BALANCEOF995(address(this));
uint _want = _balance.DIV581(2);
IERC20(want295).SAFEAPPROVE493(musd674, 0);
IERC20(want295).SAFEAPPROVE493(musd674, _want);
uint _before = _balance;
MStable(musd674).MINT666(want295, _want);
uint _after = IERC20(want295).BALANCEOF995(address(this));
supply = supply.ADD697(_before.SUB109(_after));
uint _musd = IERC20(musd674).BALANCEOF995(address(this));
uint _total = IERC20(balancer837).TOTALSUPPLY344();
uint _balancerMUSD = IERC20(musd674).BALANCEOF995(balancer837);
uint _poolAmountMUSD = _musd.MUL960(_total).DIV581(_balancerMUSD);
uint _balancerUSDC = IERC20(want295).BALANCEOF995(balancer837);
uint _poolAmountUSDC = _want.MUL960(_total).DIV581(_balancerUSDC);
uint _poolAmountOut = _poolAmountMUSD;
if (_poolAmountUSDC < _poolAmountOut) {
_poolAmountOut = _poolAmountUSDC;
}
IERC20(want295).SAFEAPPROVE493(balancer837, 0);
IERC20(want295).SAFEAPPROVE493(balancer837, _want);
IERC20(musd674).SAFEAPPROVE493(balancer837, 0);
IERC20(musd674).SAFEAPPROVE493(balancer837, _musd);
uint[] memory _maxAmountIn = new uint[](2);
_maxAmountIn[0] = _musd;
_maxAmountIn[1] = _want;
_before = IERC20(want295).BALANCEOF995(address(this));
Balancer(balancer837).JOINPOOL849(_poolAmountOut, _maxAmountIn);
_after = IERC20(want295).BALANCEOF995(address(this));
supply = supply.ADD697(_before.SUB109(_after));
}
// Controller only function for creating additional rewards from dust
function WITHDRAW505(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(address(_asset) != want295, "!c");
require(address(_asset) != musd674, "!c");
require(address(_asset) != balancer837, "!c");
balance = _asset.BALANCEOF995(address(this));
_asset.SAFETRANSFER212(controller, balance);
}
function WITHDRAWM660(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
if (_amount > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_amount);
}
uint _before = IERC20(want295).BALANCEOF995(address(this));
MStable(musd674).REDEEM500(want295, _amount);
uint _after = IERC20(want295).BALANCEOF995(address(this));
return _after.SUB109(_before);
}
function WITHDRAWBPT914(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
uint _calc = CALCULATERATIO430(_amount);
_amount = _amount.SUB109(_amount.MUL960(10).DIV581(10000));
return _WITHDRAWSOME884(_calc, _amount);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW505(uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want295).BALANCEOF995(address(this));
if (_balance < _amount) {
uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this)));
uint _remainder = _amount.SUB109(_balance);
if (_musd > 0) {
if (_musd > _remainder) {
_amount = WITHDRAWM660(_remainder);
_amount = _amount.ADD697(_balance);
} else {
_remainder = _remainder.SUB109(_musd);
uint _withdrew = WITHDRAWM660(_musd);
_amount = _withdrew.ADD697(_balance);
_withdrew = WITHDRAWBPT914(_remainder);
_amount = _amount.ADD697(_withdrew);
}
} else {
_amount = WITHDRAWBPT914(_remainder);
_amount = _amount.ADD697(_balance);
}
}
IERC20(want295).SAFETRANSFER212(controller, _amount);
}
function REDEEM500() external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
uint _balance = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this)));
if (_balance > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_balance);
}
MStable(musd674).REDEEM500(want295, _balance);
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL744() external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL952();
balance = IERC20(want295).BALANCEOF995(address(this));
IERC20(want295).SAFETRANSFER212(controller, balance);
}
function _WITHDRAWALL952() internal { //inject NONSTANDARD NAMING
uint _bpt = IERC20(balancer837).BALANCEOF995(address(this));
uint[] memory _minAmountOut = new uint[](2);
_minAmountOut[0] = 0;
_minAmountOut[1] = 0;
uint _before = IERC20(want295).BALANCEOF995(address(this));
Balancer(balancer837).EXITPOOL804(_bpt, _minAmountOut);
uint _after = IERC20(want295).BALANCEOF995(address(this));
uint _diff = _after.SUB109(_before);
if (_diff > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_after.SUB109(_before));
}
uint _musd = IERC20(musd674).BALANCEOF995(address(this));
// This one is the exception because it assumes we can redeem 1 USDC
_diff = NORMALIZE117(_musd);
if (_diff > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_diff);
}
MStable(musd674).REDEEM500(want295, _diff);
}
function CALCULATERATIO430(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(balancer837));
uint _want = IERC20(want295).BALANCEOF995(balancer837);
uint _total = _musd.ADD697(_want);
uint _ratio = _amount.MUL960(_want).DIV581(_total);
return _ratio;
}
function _WITHDRAWSOME884(uint256 _amount, uint _max) internal returns (uint) { //inject NONSTANDARD NAMING
uint _redeem = IERC20(balancer837).TOTALSUPPLY344().MUL960(_amount).DIV581(IERC20(want295).BALANCEOF995(balancer837));
if (_redeem > IERC20(balancer837).BALANCEOF995(address(this))) {
_redeem = IERC20(balancer837).BALANCEOF995(address(this));
}
uint[] memory _minAmountOut = new uint[](2);
_minAmountOut[0] = 0;
_minAmountOut[1] = 0;
uint _before = IERC20(want295).BALANCEOF995(address(this));
uint _mBefore = IERC20(musd674).BALANCEOF995(address(this));
Balancer(balancer837).EXITPOOL804(_redeem, _minAmountOut);
uint _mAfter = IERC20(musd674).BALANCEOF995(address(this));
uint _after = IERC20(want295).BALANCEOF995(address(this));
uint _musd = _mAfter.SUB109(_mBefore);
uint _withdrew = _after.SUB109(_before);
if (_withdrew > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_withdrew);
}
_musd = NORMALIZE117(_musd);
if (_musd > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_musd);
}
_before = IERC20(want295).BALANCEOF995(address(this));
MStable(musd674).REDEEM500(want295, _musd);
_after = IERC20(want295).BALANCEOF995(address(this));
_withdrew = _withdrew.ADD697(_after.SUB109(_before));
// Apply the fee as a difference
_withdrew = _withdrew.SUB109(_musd.SUB109(_after.SUB109(_before)));
if (_withdrew > _max) {
_withdrew = _max;
}
return _withdrew;
}
function NORMALIZE117(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
return _amount.MUL960(10**IERC20(want295).DECIMALS615()).DIV581(10**IERC20(musd674).DECIMALS615());
}
function BALANCEOF995() public view returns (uint) { //inject NONSTANDARD NAMING
return IERC20(want295).BALANCEOF995(address(this))
.ADD697(supply);
}
function SETGOVERNANCE741(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER847(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | inject NONSTANDARD NAMING | function SAFEAPPROVE493(IERC20 token, address spender, uint256 value) internal { | 5,414,263 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "./libraries/IDGenerator.sol";
import "./interfaces/IHologramAccumulator.sol";
import "./interfaces/IPostManager.sol";
import "./accessors/NameAccessor.sol";
import "./token/DonationPost.sol";
import "./token/RefundRequest.sol";
import "./token/Receipt.sol";
import "./token/Aurora.sol";
import "./token/Voucher.sol";
import "./token/UltraRareReceipt.sol";
import "./token/DonationReceipt.sol";
import "./base/Vault.sol";
/// @title PostManager - manages the posted items and donation flows.
/// @author Shumpei Koike - <[email protected]>
contract PostManager is IPostManager, NameAccessor {
/**
* Structs
*/
struct PostContent {
uint256 postId;
string metadata;
uint256 capacity;
uint256 periodSeconds;
uint256 startTime;
uint256 endTime;
uint256 donatedCount;
uint256 donatedSum;
bool withdrawed;
}
struct Donation {
uint256 receiptId;
uint256 postId;
uint256 serialNum;
address sender;
uint256 amount;
uint256 donateTime;
}
struct RefundStatus {
uint256 receiptId;
address claimer;
bool refuned;
}
/// @dev Maps post ID with the post content. The donee is defined in the DonationPost NFT.
mapping(uint256 => PostContent) public allPosts;
/// @dev Maps receipt ID with the donation info.
mapping(uint256 => Donation) public allDonations;
/// @dev Maps receipt ID with refund request ID.
mapping(uint256 => uint256) public refundRequests;
/// @dev Whether a voucher is necessary when posting.
bool public requireVoucher = false;
/// @dev Receipt Token ID's Seed
uint256 public nextReceiptSeed = 1;
/**
* Modifiers
*/
modifier hasVoucher() {
if (requireVoucher) require(_voucher().balanceOf(msg.sender) > 0, "AR107");
_;
}
/**
* Constructor
*/
constructor(address nameRegistry) NameAccessor(nameRegistry) {}
/// @inheritdoc IPostManager
function newPost(
string memory metadata,
uint256 capacity,
uint256 periodSeconds
) public override hasVoucher {
PostContent memory post;
post.metadata = metadata;
post.postId = _post().mint(msg.sender, metadata);
post.capacity = capacity;
post.periodSeconds = periodSeconds;
post.startTime = block.timestamp;
post.endTime = block.timestamp + periodSeconds;
allPosts[post.postId] = post;
if (requireVoucher) _voucher().useVoucher(msg.sender);
emit NewPost(
post.postId,
post.metadata,
msg.sender,
post.capacity,
post.periodSeconds,
post.startTime,
post.endTime
);
}
/// @inheritdoc IPostManager
function donate(uint256 postId, string memory metadata)
public
payable
override
{
require(allPosts[postId].postId != 0, "AR110");
address postOwner = _post().ownerOf(postId);
require(postOwner != msg.sender, "AR101");
require(allPosts[postId].endTime > block.timestamp, "AR102");
require(msg.value != 0, "AR114");
uint256 serialNum = allPosts[postId].donatedCount + 1;
uint256 receiptId = IDGenerator.donationReceiptId(
msg.sender,
nextReceiptSeed++,
serialNum
);
Donation memory donation = Donation(
receiptId,
postId,
serialNum,
msg.sender,
msg.value,
block.timestamp
);
allPosts[postId].donatedSum += msg.value;
allPosts[postId].donatedCount += 1;
allDonations[receiptId] = donation;
_receipt(receiptId).mint(msg.sender, receiptId, metadata);
emit Donate(postId, receiptId, serialNum, msg.sender, msg.value, metadata);
if (allPosts[postId].donatedCount >= allPosts[postId].capacity) {
allPosts[postId].endTime = block.timestamp;
emit ReachCapacity(
postId,
allPosts[postId].capacity,
allPosts[postId].endTime,
allPosts[postId].donatedCount,
allPosts[postId].donatedSum
);
}
_accumulator().accumulateSmall(postOwner);
}
/// @inheritdoc IPostManager
function withdraw(uint256 postId) public override {
require(_post().ownerOf(postId) == msg.sender, "AR103");
require(allPosts[postId].endTime < block.timestamp, "AR105");
require(!allPosts[postId].withdrawed, "AR111");
uint256 amount = withdrawalAmount(postId);
allPosts[postId].metadata = "";
allPosts[postId].withdrawed = true;
payable(msg.sender).transfer((amount * 9) / 10);
payable(_vault()).transfer((amount * 1) / 10);
emit Withdraw(postId, msg.sender, amount);
}
/// @inheritdoc IPostManager
function cancel(uint256 receiptId) public override {
Donation memory donation = allDonations[receiptId];
require(donation.sender == msg.sender, "AR104");
require(allPosts[donation.postId].endTime > block.timestamp, "AR102");
allPosts[donation.postId].donatedCount -= 1;
allPosts[donation.postId].donatedSum -= allDonations[receiptId].amount;
payable(msg.sender).transfer(cancelableAmount(receiptId));
_receipt(receiptId).burn(receiptId);
delete allDonations[receiptId];
emit CancelDonation(
donation.postId,
receiptId,
msg.sender,
donation.amount
);
_accumulator().undermineSmall(_post().ownerOf(donation.postId));
}
/// @inheritdoc IPostManager
function requestRefund(uint256 receiptId, string memory metadata)
public
override
{
uint256 postId = allDonations[receiptId].postId;
require(_receipt(receiptId).ownerOf(receiptId) == msg.sender, "AR104");
require(allPosts[postId].endTime < block.timestamp, "AR105");
require(refundRequests[receiptId] == 0, "AR112");
uint256 requestId = IDGenerator.requestId(msg.sender, receiptId);
address donee = _post().ownerOf(postId);
_refund().mint(donee, requestId, metadata);
refundRequests[receiptId] = requestId;
emit RequestRefund(requestId, msg.sender, receiptId, metadata);
_accumulator().undermineMedium(donee);
}
/// @inheritdoc IPostManager
function refund(uint256 receiptId) public payable override {
uint256 postId = allDonations[receiptId].postId;
require(allPosts[postId].endTime < block.timestamp, "AR105");
require(allDonations[receiptId].amount == msg.value, "AR109");
uint256 requestId = refundRequests[receiptId];
require(_refund().ownerOf(requestId) == msg.sender, "AR108");
delete refundRequests[receiptId];
payable(_receipt(receiptId).ownerOf(receiptId)).transfer(msg.value);
_receipt(receiptId).burn(receiptId);
_refund().burn(requestId);
emit Refund(receiptId, postId, requestId, msg.value);
_accumulator().accumulateLarge(msg.sender);
}
/// @inheritdoc IPostManager
function totalValueLocked() public view override returns (uint256) {
return address(this).balance;
}
/// @dev Computes a refund request ID.
/// @param account address of the account
/// @param receiptId uint256 of the payment ID
function computeRefundRequestId(address account, uint256 receiptId)
public
pure
returns (uint256)
{
return IDGenerator.requestId(account, receiptId);
}
/// @dev Computes a receipt ID.
/// @param account address of the account
/// @param seed uint256 of the seed number
/// @param serialNum uint256 of the serial number
function computeDonationReceiptId(
address account,
uint256 seed,
uint256 serialNum
) public pure returns (uint256) {
return IDGenerator.donationReceiptId(account, seed, serialNum);
}
/// @dev Gets the cancelable amount.
/// @param receiptId uint256 of the payment ID
function cancelableAmount(uint256 receiptId) public view returns (uint256) {
uint256 postId = allDonations[receiptId].postId;
return
allPosts[postId].endTime > block.timestamp
? allDonations[receiptId].amount
: 0;
}
/// @dev Gets the withdrawal amount.
/// @param postId uint256 of the post ID
function withdrawalAmount(uint256 postId) public view returns (uint256) {
return
allPosts[postId].endTime < block.timestamp
? allPosts[postId].donatedSum
: 0;
}
/// @inheritdoc IPostManager
function isOpen(uint256 postId) public view override returns (bool) {
return allPosts[postId].endTime > block.timestamp;
}
/// @dev Checks if the receipt is a rare or not.
function isRare(uint256 receiptId) public pure returns (bool) {
return receiptId % 10 == 7;
}
/// @dev Switches if it is necessary to use a voucher when positing a new.
function switchVoucherRequirement() public onlyOwner {
requireVoucher = !requireVoucher;
}
function _aurora() internal view returns (Aurora) {
return Aurora(auroraAddress());
}
function _post() internal view returns (DonationPost) {
return DonationPost(postAddress());
}
function _receipt(uint256 receiptId) internal view returns (Receipt) {
return
isRare(receiptId)
? Receipt(ultraRareAddress())
: Receipt(receiptAddress());
}
function _refund() internal view returns (RefundRequest) {
return RefundRequest(refundAddress());
}
function _voucher() internal view returns (Voucher) {
return Voucher(voucherAddress());
}
function _accumulator() internal view returns (IHologramAccumulator) {
return IHologramAccumulator(accumulatorAddress());
}
function _vault() internal view returns (Vault) {
return Vault(payable(vaultAddress()));
}
}
| Gets the cancelable amount. receiptId uint256 of the payment ID | function cancelableAmount(uint256 receiptId) public view returns (uint256) {
uint256 postId = allDonations[receiptId].postId;
return
allPosts[postId].endTime > block.timestamp
? allDonations[receiptId].amount
: 0;
}
| 14,076,537 |
./partial_match/3/0x8e1f2580D4759fFBF7d38Ff319348B5373A7Ee1a/sources/AURA.sol | Dev fee Tax fee Take liquidity fee | function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) {
uint256 transferAmount = amount;
if(_devFee != 0){
uint256 devFee = amount.mul(_devFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(devFee);
_reflectionTotal = _reflectionTotal.sub(devFee.mul(rate));
_devFeeTotal = _devFeeTotal.add(devFee);
emit RewardsDistributed(devFee);
}
if(_taxFee != 0){
uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(taxFee);
_reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate));
_taxFeeTotal = _taxFeeTotal.add(taxFee);
emit RewardsDistributed(taxFee);
}
if(_liquidityFee != 0){
uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(liquidityFee);
_reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate));
_liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee);
emit Transfer(account,address(this),liquidityFee);
}
return transferAmount;
}
| 5,172,088 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {ChainlinkClient} from '@chainlink/contracts/src/v0.8/ChainlinkClient.sol';
import {Chainlink} from '@chainlink/contracts/src/v0.8/Chainlink.sol';
import {IERC677} from './interfaces/IERC677.sol';
import {IOracleTestConsumer} from './interfaces/IOracleTestConsumer.sol';
contract OracleTestConsumer is IOracleTestConsumer, ChainlinkClient, Ownable {
using Chainlink for Chainlink.Request;
constructor(address link) Ownable() {
setChainlinkToken(link);
}
uint256 public override latestResponseUInt256;
mapping(bytes32 => uint256) public override responseUInt256;
/***** Runlog request *****/
function requestGetUInt256(
address oracle,
string memory jobId,
uint256 payment,
string memory url,
string memory path,
int256 times
) public override onlyOwner returns (bytes32 requestId) {
Chainlink.Request memory req = buildChainlinkRequest(
stringToBytes32(jobId),
address(this),
this.fulfillUInt256.selector
);
req.add('url', url);
req.add('path', path);
req.addInt('times', times);
requestId = sendChainlinkRequestTo(oracle, req, payment);
emit RequestUInt256(requestId, oracle, jobId, payment, url, path, times);
}
function fulfillUInt256(bytes32 requestId, uint256 response) public override recordChainlinkFulfillment(requestId) {
responseUInt256[requestId] = response;
latestResponseUInt256 = response;
emit FullfillUInt256(requestId, response);
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
) public override onlyOwner {
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
/***** Token Info *****/
function getChainlinkToken() public view override returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public override onlyOwner {
IERC677 link = IERC677(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), 'Unable to transfer');
}
/***** Utils *****/
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
// solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
| Token Info / | function getChainlinkToken() public view override returns (address) {
return chainlinkTokenAddress();
}
| 15,830,257 |
./full_match/5/0x3389289123be1DD020aC09c631d8C68470Bdad2C/sources/browser/Escrow.sol | Abort the purchase and reclaim the ether. Can only be called by the seller before the contract is locked. We use transfer here directly. It is reentrancy-safe, because it is the last call in this function and we already changed the state. | function abort()
public
onlySeller
inState(State.Created)
{
emit Aborted();
state = State.Inactive;
seller.transfer(address(this).balance);
}
| 1,865,603 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ICheque.sol";
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functios using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*
* _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._
*/
contract Cheque is
Context,
Ownable,
ERC721Enumerable,
ERC721Pausable,
ICheque
{
using Counters for Counters.Counter;
uint256 public maxSupply;
Counters.Counter private _tokenIdTracker;
address private _proxy;
string private _baseTokenURI;
constructor(
string memory name,
string memory symbol,
string memory baseTokenURI,
uint256 maxTokenSupply,
address proxy
) ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
maxSupply = maxTokenSupply;
_tokenIdTracker.increment();
_proxy = proxy;
}
modifier onlyProxy() {
require(_msgSender() == _proxy, "Only proxy can perform this action");
_;
}
function mintedCount() external view returns (uint256) {
return _tokenIdTracker.current() - 1;
}
function setBaseURI(string memory uri) external onlyOwner {
_baseTokenURI = uri;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function mint(address to) public virtual onlyProxy returns (uint256) {
require(_tokenIdTracker.current() <= maxSupply, "Max supply reached");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
return _tokenIdTracker.current() - 1;
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_msgSender() == _proxy || _isApprovedOrOwner(_msgSender(), tokenId), "Caller is not proxy, owner nor approved");
_burn(tokenId);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external virtual onlyOwner {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external virtual onlyOwner {
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// 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/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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) 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/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 (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: Unlicense
pragma solidity ^0.8.0;
interface ICheque {
function setBaseURI(string memory uri) external;
function mintedCount() external view returns (uint256);
}
// 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/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
// 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 (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 (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 v4.4.1 (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, _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 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 v4.4.1 (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 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;
} | Unpauses all token transfers. See {ERC721Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./ | function unpause() external virtual onlyOwner {
_unpause();
}
| 184,663 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import { Chess } from "./Chess.sol";
import { Engine } from "./Engine.sol";
import { fiveoutofnineART } from "./fiveoutofnineART.sol";
/// @title fiveoutofnine NFT - the first 100% on-chain chess engine.
/// @author fiveoutofnine
/// @notice This file has few docstrings (by choice) because most of it is standard. Refer to
/// {Chess}, {Engine}, and {fiveoutofnineART} for thorough documentation.
contract fiveoutofnine is ERC721, Ownable, ReentrancyGuard {
using Chess for uint256;
using Strings for uint256;
uint256 public board;
uint256 private internalId;
mapping(uint256 => uint256) public tokenInternalIds;
mapping(uint256 => Chess.Move) public tokenMoves;
uint256 public totalSupply;
string private baseURI;
constructor() ERC721("fiveoutofnine", unicode"♞") {
honorableMints();
board = 0x32562300110101000010010000000C0099999000BCDE0B000000001;
internalId = (1 << 0x80) | 2;
totalSupply = 11;
}
function mintMove(uint256 _move, uint256 _depth) external payable nonReentrant {
require(_depth >= 3 && _depth <= 10);
require((internalId >> 0x80) < 59 && uint128(internalId) < 59);
playMove(_move, _depth);
_safeMint(msg.sender, totalSupply++);
}
function playMove(uint256 _move, uint256 _depth) internal {
unchecked {
uint256 inMemoryBoard = board;
require(inMemoryBoard.isLegalMove(_move));
inMemoryBoard = inMemoryBoard.applyMove(_move);
(uint256 bestMove, bool isWhiteCheckmated) = Engine.searchMove(inMemoryBoard, _depth);
tokenInternalIds[totalSupply] = internalId++;
tokenMoves[totalSupply] = Chess.Move(board, (_depth << 24) | (_move << 12) | bestMove);
if (bestMove == 0 || uint128(internalId) >= 59) {
resetBoard();
} else {
board = inMemoryBoard.applyMove(bestMove);
if (isWhiteCheckmated) {
resetBoard();
}
}
}
}
function resetBoard() internal {
board = 0x3256230011111100000000000000000099999900BCDECB000000001;
internalId = ((internalId >> 0x80) + 1) << 0x80;
}
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
return bytes(baseURI).length == 0
? _tokenURI(_tokenId)
: string(abi.encodePacked(baseURI, _tokenId.toString()));
}
function _tokenURI(uint256 _tokenId) public view returns (string memory) {
return fiveoutofnineART.getMetadata(tokenInternalIds[_tokenId], tokenMoves[_tokenId]);
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function honorableMints() internal {
_safeMint(0xA85572Cd96f1643458f17340b6f0D6549Af482F5, 0);
tokenInternalIds[0] = 0;
tokenMoves[0] = Chess.Move(
0x3256230011111100000000000000000099999900BCDECB000000001,
0x851C4A2
);
_safeMint(0x3759328b1CE944642d36a61F06783f2865212515, 1);
tokenInternalIds[1] = 1;
tokenMoves[1] = Chess.Move(
0x3256230010111100000000000190000099099900BCDECB000000001,
0x759E51C
);
_safeMint(0xFD8eA0F05dB884A78B1A1C1B3767B9E5D6664764, 2);
tokenInternalIds[2] = 2;
tokenMoves[2] = Chess.Move(
0x3256230010101100000100009190000009099900BCDECB000000001,
0x64DB565
);
_safeMint(0x174787a207BF4eD4D8db0945602e49f42c146474, 3);
tokenInternalIds[3] = 3;
tokenMoves[3] = Chess.Move(
0x3256230010100100000100009199100009009900BCDECB000000001,
0x645A725
);
_safeMint(0x6dEa5dCFa64DC0bb4E5AC53A375A4377CF4eD0Ee, 4);
tokenInternalIds[4] = 4;
tokenMoves[4] = Chess.Move(
0x3256230010100100000000009199100009009000BCDECB000000001,
0x631A4DB
);
_safeMint(0x333601a803CAc32B7D17A38d32c9728A93b422f4, 5);
tokenInternalIds[5] = 5;
tokenMoves[5] = Chess.Move(
0x3256230010000100001000009199D00009009000BC0ECB000000001,
0x6693315
);
_safeMint(0x530cF036Ed4Fa58f7301a9C788C9806624ceFD19, 6);
tokenInternalIds[6] = 6;
tokenMoves[6] = Chess.Move(
0x32502300100061000010000091990000090D9000BC0ECB000000001,
0x64E1554
);
_safeMint(0xD6A9cB7aB95293a7D38f416Cd3A4Fe9059CCd5B2, 7);
tokenInternalIds[7] = 7;
tokenMoves[7] = Chess.Move(
0x325023001006010000100D009199000009009000BC0ECB000000001,
0x63532A5
);
_safeMint(0xaFDc1A3EF3992f53C10fC798d242E15E2F0DF51A, 8);
tokenInternalIds[8] = 8;
tokenMoves[8] = Chess.Move(
0x305023001006010000100D0091992000090C9000B00ECB000000001,
0x66E4000
);
_safeMint(0xC1A80D351232fD07EE5733b5F581E01C269068A9, 9);
tokenInternalIds[9] = 1 << 0x80;
tokenMoves[9] = Chess.Move(
0x3256230011111100000000000000000099999900BCDECB000000001,
0x646155E
);
_safeMint(0xF42D1c0c0165AF5625b2ecD5027c5C5554e5b039, 10);
tokenInternalIds[10] = (1 << 0x80) | 1;
tokenMoves[10] = Chess.Move(
0x3256230011110100000001000000000099999000BCDECB000000001,
0x62994DB
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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
pragma solidity ^0.8.9;
import { Engine } from "./Engine.sol";
/// @title Utils library for fiveoutofnine (a 100% on-chain 6x6 chess engine)
/// @author fiveoutofnine
/// @dev Understand the representations of the chess pieces, board, and moves very carefully before
/// using this library:
/// ======================================Piece Representation======================================
/// Each chess piece is defined with 4 bits as follows:
/// * The first bit denotes the color (0 means black; 1 means white).
/// * The last 3 bits denote the type:
/// | Bits | # | Type |
/// | ---- | - | ------ |
/// | 000 | 0 | Empty |
/// | 001 | 1 | Pawn |
/// | 010 | 2 | Bishop |
/// | 011 | 3 | Rook |
/// | 100 | 4 | Knight |
/// | 101 | 5 | Queen |
/// | 110 | 6 | King |
/// ======================================Board Representation======================================
/// The board is an 8x8 representation of a 6x6 chess board. For efficiency, all information is
/// bitpacked into a single uint256. Thus, unlike typical implementations, board positions are
/// accessed via bit shifts and bit masks, as opposed to array accesses. Since each piece is 4 bits,
/// there are 64 ``indices'' to access:
/// 63 62 61 60 59 58 57 56
/// 55 54 53 52 51 50 49 48
/// 47 46 45 44 43 42 41 40
/// 39 38 37 36 35 34 33 32
/// 31 30 29 28 27 26 25 24
/// 23 22 21 20 19 18 17 16
/// 15 14 13 12 11 10 09 08
/// 07 06 05 04 03 02 01 00
/// All numbers in the figure above are in decimal representation.
/// For example, the piece at index 27 is accessed with ``(board >> (27 << 2)) & 0xF''.
///
/// The top/bottom rows and left/right columns are treated as sentinel rows/columns for efficient
/// boundary validation (see {Chess-generateMoves} and {Chess-isValid}). i.e., (63, ..., 56),
/// (07, ..., 00), (63, ..., 07), and (56, ..., 00) never contain pieces. Every bit in those rows
/// and columns should be ignored, except for the last bit. The last bit denotes whose turn it is to
/// play (0 means black's turn; 1 means white's turn). e.g. a potential starting position:
/// Black
/// 00 00 00 00 00 00 00 00 Black
/// 00 03 02 05 06 02 03 00 ♜ ♝ ♛ ♚ ♝ ♜
/// 00 01 01 01 01 01 01 00 ♟ ♟ ♟ ♟ ♟ ♟
/// 00 00 00 00 00 00 00 00 denotes
/// 00 00 00 00 00 00 00 00 the board
/// 00 09 09 09 09 09 09 00 ♙ ♙ ♙ ♙ ♙ ♙
/// 00 11 12 13 14 12 11 00 ♖ ♘ ♕ ♔ ♘ ♖
/// 00 00 00 00 00 00 00 01 White
/// White
/// All numbers in the example above are in decimal representation.
/// ======================================Move Representation=======================================
/// Each move is allocated 12 bits. The first 6 bits are the index the piece is moving from, and the
/// last 6 bits are the index the piece is moving to. Since the index representing a square is at
/// most 54, 6 bits sufficiently represents any index (0b111111 = 63 > 54). e.g. 1243 denotes a move
/// from index 19 to 27 (1243 = (19 << 6) | 27).
///
/// Since the board is represented by a uint256, consider including ``using Chess for uint256''.
library Chess {
using Chess for uint256;
using Chess for Chess.MovesArray;
/// The depth, white's move, and black's move are bitpacked in that order as `metadata` for
/// efficiency. As explained above, 12 bits sufficiently describe a move, so both white's and
/// black's moves are allocated 12 bits each.
struct Move {
uint256 board;
uint256 metadata;
}
/// ``moves'' are bitpacked into uint256s for efficiency. Since every move is defined by at most
/// 12 bits, a uint256 can contain up to 21 moves via bitpacking (21 * 12 = 252 < 256).
/// Therefore, `items` can contain up to 21 * 5 = 105 moves. 105 is a safe upper bound for the
/// number of possible moves a given side may have during a real game, but be wary because there
/// is no formal proof of the upper bound being less than or equal to 105.
struct MovesArray {
uint256 index;
uint256[5] items;
}
/// @notice Takes in a board position, and applies the move `_move` to it.
/// @dev After applying the move, the board's perspective is updated (see {rotate}). Thus,
/// engines with symmterical search algorithms -- like negamax search -- probably work best.
/// @param _board The board to apply the move to.
/// @param _move The move to apply.
/// @return The reversed board after applying `_move` to `_board`.
function applyMove(uint256 _board, uint256 _move) internal pure returns (uint256) {
unchecked {
// Get piece at the from index
uint256 piece = (_board >> ((_move >> 6) << 2)) & 0xF;
// Replace 4 bits at the from index with 0000
_board &= type(uint256).max ^ (0xF << ((_move >> 6) << 2));
// Replace 4 bits at the to index with 0000
_board &= type(uint256).max ^ (0xF << ((_move & 0x3F) << 2));
// Place the piece at the to index
_board |= (piece << ((_move & 0x3F) << 2));
return _board.rotate();
}
}
/// @notice Switches the perspective of the board by reversing its 4-bit subdivisions (e.g.
/// 1100-0011 would become 0011-1100).
/// @dev Since the last bit exchanges positions with the 4th bit, the turn identifier is updated
/// as well.
/// @param _board The board to reverse the perspective on.
/// @return `_board` reversed.
function rotate(uint256 _board) internal pure returns (uint256) {
uint256 rotatedBoard;
unchecked {
for (uint256 i; i < 64; ++i) {
rotatedBoard = (rotatedBoard << 4) | (_board & 0xF);
_board >>= 4;
}
}
return rotatedBoard;
}
/// @notice Generates all possible pseudolegal moves for a given position and color.
/// @dev The last bit denotes which color to generate the moves for (see {Chess}). Also, the
/// function errors if more than 105 moves are found (see {Chess-MovesArray}). All moves are
/// expressed in code as shifts respective to the board's 8x8 representation (see {Chess}).
/// @param _board The board position to generate moves for.
/// @return Bitpacked uint256(s) containing moves.
function generateMoves(uint256 _board) internal pure returns (uint256[5] memory) {
Chess.MovesArray memory movesArray;
uint256 move;
uint256 moveTo;
unchecked {
// `0xDB5D33CB1BADB2BAA99A59238A179D71B69959551349138D30B289` is a mapping of indices
// relative to the 6x6 board to indices relative to the 8x8 representation (see
// {Chess-getAdjustedIndex}).
for (
uint256 index = 0xDB5D33CB1BADB2BAA99A59238A179D71B69959551349138D30B289;
index != 0;
index >>= 6
) {
uint256 adjustedIndex = index & 0x3F;
uint256 adjustedBoard = _board >> (adjustedIndex << 2);
uint256 piece = adjustedBoard & 0xF;
// Skip if square is empty or not the color of the board the function call is
// analyzing.
if (piece == 0 || piece >> 3 != _board & 1) continue;
// The first bit can be discarded because the if statement above catches all
// redundant squares.
piece &= 7;
if (piece == 1) { // Piece is a pawn.
// 1 square in front of the pawn is empty.
if ((adjustedBoard >> 0x20) & 0xF == 0) {
movesArray.append(adjustedIndex, adjustedIndex + 8);
// The pawn is in its starting row and 2 squares in front is empty. This
// must be nested because moving 2 squares would not be valid if there was
// an obstruction 1 square in front (i.e. pawns can not jump over pieces).
if (adjustedIndex >> 3 == 2 && (adjustedBoard >> 0x40) & 0xF == 0) {
movesArray.append(adjustedIndex, adjustedIndex + 0x10);
}
}
// Moving to the right diagonal by 1 captures a piece.
if (_board.isCapture(adjustedBoard >> 0x1C)) {
movesArray.append(adjustedIndex, adjustedIndex + 7);
}
// Moving to the left diagonal by 1 captures a piece.
if (_board.isCapture(adjustedBoard >> 0x24)) {
movesArray.append(adjustedIndex, adjustedIndex + 9);
}
} else if (piece > 3 && piece & 1 == 0) { // Piece is a knight or a king.
// Knights and kings always only have 8 positions to check relative to their
// current position, and the relative distances are always the same. For
// knights, positions to check are ±{6, 10, 15, 17}. This is bitpacked into
// `0x060A0F11` to reduce code redundancy. Similarly, the positions to check for
// kings are ±{1, 7, 8, 9}, which is `0x01070809` when bitpacked.
for (move = piece == 4 ? 0x060A0F11 : 0x01070809; move != 0; move >>= 8) {
if (_board.isValid(moveTo = adjustedIndex + (move & 0xFF))) {
movesArray.append(adjustedIndex, moveTo);
}
if (move <= adjustedIndex
&& _board.isValid(moveTo = adjustedIndex - (move & 0xFF)))
{
movesArray.append(adjustedIndex, moveTo);
}
}
} else {
// This else block generates moves for all sliding pieces. All of the 8 for
// loops terminate
// * before a sliding piece makes an illegal move
// * or after a sliding piece captures a piece.
if (piece != 2) { // Ortholinear pieces (i.e. rook and queen)
for (move = adjustedIndex + 1; _board.isValid(move); move += 1) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex - 1; _board.isValid(move); move -= 1) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex + 8; _board.isValid(move); move += 8) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex - 8; _board.isValid(move); move -= 8) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
}
if (piece != 3) { // Diagonal pieces (i.e. bishop and queen)
for (move = adjustedIndex + 7; _board.isValid(move); move += 7) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex - 7; _board.isValid(move); move -= 7) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex + 9; _board.isValid(move); move += 9) {
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
for (move = adjustedIndex - 9; _board.isValid(move); move -= 9) {
// Handles the edge case where a white bishop believes it can capture
// the ``piece'' at index 0, when it is actually the turn identifier It
// would mistakenly believe it is valid move via capturing a black pawn.
if (move == 0) break;
movesArray.append(adjustedIndex, move);
if (_board.isCapture(_board >> (move << 2))) break;
}
}
}
}
}
return movesArray.items;
}
/// @notice Determines whether a move is a legal move or not (includes checking whether king is
/// checked or not after the move).
/// @param _board The board to analyze.
/// @param _move The move to check.
/// @return Whether the move is legal or not.
function isLegalMove(uint256 _board, uint256 _move) internal pure returns (bool) {
unchecked {
uint256 fromIndex = _move >> 6;
uint256 toIndex = _move & 0x3F;
if ((0x7E7E7E7E7E7E00 >> fromIndex) & 1 == 0) return false;
if ((0x7E7E7E7E7E7E00 >> toIndex) & 1 == 0) return false;
uint256 pieceAtFromIndex = (_board >> (fromIndex << 2)) & 0xF;
if (pieceAtFromIndex == 0) return false;
if (pieceAtFromIndex >> 3 != _board & 1) return false;
pieceAtFromIndex &= 7;
uint256 adjustedBoard = _board >> (toIndex << 2);
uint256 indexChange = toIndex < fromIndex
? fromIndex - toIndex
: toIndex - fromIndex;
if (pieceAtFromIndex == 1) {
if (toIndex <= fromIndex) return false;
indexChange = toIndex - fromIndex;
if ((indexChange == 7 || indexChange == 9)) {
if (!_board.isCapture(adjustedBoard)) return false;
} else if (indexChange == 8) {
if (!isValid(_board, toIndex)) return false;
} else if (indexChange == 0x10) {
if (!isValid(_board, toIndex - 8) || !isValid(_board, toIndex)) return false;
} else {
return false;
}
} else if (pieceAtFromIndex == 4 || pieceAtFromIndex == 6) {
if (((pieceAtFromIndex == 4 ? 0x28440 : 0x382) >> indexChange) & 1 == 0) {
return false;
}
if (!isValid(_board, toIndex)) return false;
} else {
bool rayFound;
if (pieceAtFromIndex != 2) {
rayFound = searchRay(_board, fromIndex, toIndex, 1)
|| searchRay(_board, fromIndex, toIndex, 8);
}
if (pieceAtFromIndex != 3) {
rayFound = rayFound
|| searchRay(_board, fromIndex, toIndex, 7)
|| searchRay(_board, fromIndex, toIndex, 9);
}
if (!rayFound) return false;
}
if (Engine.negaMax(_board.applyMove(_move), 1) < -1_260) return false;
return true;
}
}
/// @notice Determines whether there is a clear path along a direction vector from one index to
/// another index on the board.
/// @dev The board's representation essentially flattens it from 2D to 1D, so `_directionVector`
/// should be the change in index that represents the direction vector.
/// @param _board The board to analyze.
/// @param _fromIndex The index of the starting piece.
/// @param _toIndex The index of the ending piece.
/// @param _directionVector The direction vector of the ray.
/// @return Whether there is a clear path between `_fromIndex` and `_toIndex` or not.
function searchRay(
uint256 _board,
uint256 _fromIndex,
uint256 _toIndex,
uint256 _directionVector
)
internal pure
returns (bool)
{
unchecked {
uint256 indexChange;
uint256 rayStart;
uint256 rayEnd;
if (_fromIndex < _toIndex) {
indexChange = _toIndex - _fromIndex;
rayStart = _fromIndex + _directionVector;
rayEnd = _toIndex;
} else {
indexChange = _fromIndex - _toIndex;
rayStart = _toIndex;
rayEnd = _fromIndex - _directionVector;
}
if (indexChange % _directionVector != 0) return false;
for (
rayStart = rayStart;
rayStart < rayEnd;
rayStart += _directionVector
) {
if (!isValid(_board, rayStart)) return false;
if (isCapture(_board, _board >> (rayStart << 2))) return false;
}
if (!isValid(_board, rayStart)) return false;
return rayStart == rayEnd;
}
}
/// @notice Determines whether a move results in a capture or not.
/// @param _board The board prior to the potential capture.
/// @param _indexAdjustedBoard The board bitshifted to the to index to consider.
/// @return Whether the move is a capture or not.
function isCapture(uint256 _board, uint256 _indexAdjustedBoard) internal pure returns (bool) {
unchecked {
return (_indexAdjustedBoard & 0xF) != 0 // The square is not empty.
&& (_indexAdjustedBoard & 0xF) >> 3 != _board & 1; // The piece is opposite color.
}
}
/// @notice Determines whether a move is valid or not (i.e. within bounds and not capturing
/// same colored piece).
/// @dev As mentioned above, the board representation has 2 sentinel rows and columns for
/// efficient boundary validation as follows:
/// 0 0 0 0 0 0 0 0
/// 0 1 1 1 1 1 1 0
/// 0 1 1 1 1 1 1 0
/// 0 1 1 1 1 1 1 0
/// 0 1 1 1 1 1 1 0
/// 0 1 1 1 1 1 1 0
/// 0 1 1 1 1 1 1 0
/// 0 0 0 0 0 0 0 0,
/// where 1 means a piece is within the board, and 0 means the piece is out of bounds. The bits
/// are bitpacked into a uint256 (i.e. ``0x7E7E7E7E7E7E00 = 0 << 63 | ... | 0 << 0'') for
/// efficiency.
///
/// Moves that overflow the uint256 are computed correctly because bitshifting more than bits
/// available results in 0. However, moves that underflow the uint256 (i.e. applying the move
/// results in a negative index) must be checked beforehand.
/// @param _board The board on which to consider whether the move is valid.
/// @param _toIndex The to index of the move.
/// @return Whether the move is valid or not.
function isValid(uint256 _board, uint256 _toIndex) internal pure returns (bool) {
unchecked {
return (0x7E7E7E7E7E7E00 >> _toIndex) & 1 == 1 // Move is within bounds.
&& ((_board >> (_toIndex << 2)) & 0xF == 0 // Square is empty.
|| (((_board >> (_toIndex << 2)) & 0xF) >> 3) != _board & 1); // Piece captured.
}
}
/// @notice Maps an index relative to the 6x6 board to the index relative to the 8x8
/// representation.
/// @dev The indices are mapped as follows:
/// 35 34 33 32 31 30 54 53 52 51 50 49
/// 29 28 27 26 25 24 46 45 44 43 42 41
/// 23 22 21 20 19 18 mapped 38 37 36 35 34 33
/// 17 16 15 14 13 12 to 30 29 28 27 26 25
/// 11 10 09 08 07 06 22 21 20 19 18 17
/// 05 04 03 02 01 00 14 13 12 11 10 09
/// All numbers in the figure above are in decimal representation. The bits are bitpacked into a
/// uint256 (i.e. ``0xDB5D33CB1BADB2BAA99A59238A179D71B69959551349138D30B289 = 54 << (6 * 35) |
/// ... | 9 << (6 * 0)'') for efficiency.
/// @param _index Index relative to the 6x6 board.
/// @return Index relative to the 8x8 representation.
function getAdjustedIndex(uint256 _index) internal pure returns (uint256) {
unchecked {
return (
(0xDB5D33CB1BADB2BAA99A59238A179D71B69959551349138D30B289 >> (_index * 6)) & 0x3F
);
}
}
/// @notice Appends a move to a {Chess-MovesArray} object.
/// @dev Since each uint256 fits at most 21 moves (see {Chess-MovesArray}), {Chess-append}
/// bitpacks 21 moves per uint256 before moving on to the next uint256.
/// @param _movesArray {Chess-MovesArray} object to append the new move to.
/// @param _fromMoveIndex Index the piece moves from.
/// @param _toMoveIndex Index the piece moves to.
function append(MovesArray memory _movesArray, uint256 _fromMoveIndex, uint256 _toMoveIndex)
internal pure
{
unchecked {
uint256 currentIndex = _movesArray.index;
uint256 currentPartition = _movesArray.items[currentIndex];
if (currentPartition > (1 << 0xF6)) {
_movesArray.items[++_movesArray.index] = (_fromMoveIndex << 6) | _toMoveIndex;
} else {
_movesArray.items[currentIndex] = (currentPartition << 0xC)
| (_fromMoveIndex << 6)
| _toMoveIndex;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import { Chess } from "./Chess.sol";
/// @title A 6x6 chess engine with negamax search
/// @author fiveoutofnine
/// @notice Docstrings below are written from the perspective of black (i.e. written as if the
/// engine is always black). However, due to negamax's symmetric nature, the engine may be used for
/// white as well.
library Engine {
using Chess for uint256;
using Engine for uint256;
/// @notice Searches for the ``best'' move.
/// @dev The ply depth must be at least 3 because game ending scenarios are determined lazily.
/// This is because {generateMoves} generates pseudolegal moves. Consider the following:
/// 1. In the case of white checkmates black, depth 2 is necessary:
/// * Depth 1: This is the move black plays after considering depth 2.
/// * Depth 2: Check whether white captures black's king within 1 turn for every such
/// move. If so, white has checkmated black.
/// 2. In the case of black checkmates white, depth 3 is necessary:
/// * Depth 1: This is the move black plays after considering depths 2 and 3.
/// * Depth 2: Generate all pseudolegal moves for white in response to black's move.
/// * Depth 3: Check whether black captures white's king within 1 turn for every such
/// * move. If so, black has checkmated white.
/// The minimum depth required to cover all the cases above is 3. For simplicity, stalemates
/// are treated as checkmates.
///
/// The function returns 0 if the game is over after white's move (no collision with any
/// potentially real moves because 0 is not a valid index), and returns true if the game is over
/// after black's move.
/// @param _board The board position to analyze.
/// @param _depth The ply depth to analyze to. Must be at least 3.
/// @return The best move for the player (denoted by the last bit in `_board`).
/// @return Whether white is checkmated or not.
function searchMove(uint256 _board, uint256 _depth) internal pure returns (uint256, bool) {
uint256[5] memory moves = _board.generateMoves();
if (moves[0] == 0) return (0, false);
// See {Engine-negaMax} for explanation on why `bestScore` is set to -4_196.
int256 bestScore = -4_196;
int256 currentScore;
uint256 bestMove;
unchecked {
for (uint256 i; moves[i] != 0; ++i) {
for (uint256 movePartition = moves[i]; movePartition != 0; movePartition >>= 0xC) {
currentScore = _board.evaluateMove(movePartition & 0xFFF)
+ negaMax(_board.applyMove(movePartition & 0xFFF), _depth - 1);
if (currentScore > bestScore) {
bestScore = currentScore;
bestMove = movePartition & 0xFFF;
}
}
}
}
// 1_260 is equivalent to 7 queens (7 * 180 = 1260). Since a king's capture is equivalent to
// an evaluation of 4_000, ±1_260 catches all lines that include the capture of a king.
if (bestScore < -1_260) return (0, false);
return (bestMove, bestScore > 1_260);
}
/// @notice Searches and evaluates moves using a variant of the negamax search algorithm.
/// @dev For efficiency, the function evaluates how good moves are and sums them up, rather than
/// evaluating entire board positions. Thus, the only pruning the algorithm performs is when a
/// king is captured. If a king is captured, it always returns -4,000, which is the king's value
/// (see {Chess}) because there is nothing more to consider.
/// @param _board The board position to analyze.
/// @param _depth The ply depth to analyze to.
/// @return The cumulative score searched to a ply depth of `_depth`, assuming each side picks
/// their ``best'' (as decided by {Engine-evaluateMove}) moves.
function negaMax(uint256 _board, uint256 _depth) internal pure returns (int256) {
// Base case for the recursion.
if (_depth == 0) return 0;
uint256[5] memory moves = _board.generateMoves();
// There is no ``best'' score if there are no moves to play.
if (moves[0] == 0) return 0;
// `bestScore` is initially set to -4_196 because no line will result in a cumulative
// evaluation of <-4_195. -4_195 occurs, for example. when the engine's king is captured
// (-4000), and the player captures an engine's queen on index 35 (-181) with knight from
// index 52 (-14).
int256 bestScore = -4_196;
int256 currentScore;
uint256 bestMove;
unchecked {
for (uint256 i; moves[i] != 0; ++i) {
for (uint256 movePartition = moves[i]; movePartition != 0; movePartition >>= 0xC) {
currentScore = _board.evaluateMove(movePartition & 0xFFF);
if (currentScore > bestScore) {
bestScore = currentScore;
bestMove = movePartition & 0xFFF;
}
}
}
// If a king is captured, stop the recursive call stack and return a score of -4_000.
// There is nothing more to consider.
if (((_board >> ((bestMove & 0x3F) << 2)) & 7) == 6) return -4_000;
return _board & 1 == 0
? bestScore + negaMax(_board.applyMove(bestMove), _depth - 1)
: -bestScore + negaMax(_board.applyMove(bestMove), _depth - 1);
}
}
/// @notice Uses piece-square tables (PSTs) to evaluate how ``good'' a move is.
/// @dev The PSTs were selected semi-arbitrarily with chess strategies in mind (e.g. pawns are
/// good in the center). Updating them changes the way the engine ``thinks.'' Each piece's PST
/// is bitpacked into as few uint256s as possible for efficiency (see {Engine-getPst} and
/// {Engine-getPstTwo}):
/// Pawn Bishop Knight Rook
/// 20 20 20 20 20 20 62 64 64 64 64 62 54 56 54 54 56 58 100 100 100 100 100 100
/// 30 30 30 30 30 30 64 66 66 66 66 64 56 60 64 64 60 56 101 102 102 102 102 101
/// 20 22 24 24 22 20 64 67 68 68 67 64 58 64 68 68 64 58 99 100 100 100 100 99
/// 21 20 26 26 20 21 64 68 68 68 68 64 58 65 68 68 65 58 99 100 100 100 100 99
/// 21 30 16 16 30 21 64 67 66 66 67 64 56 60 65 65 60 56 99 100 100 100 100 99
/// 20 20 20 20 20 20 62 64 64 64 64 62 54 56 58 58 56 54 100 100 101 101 100 100
/// Queen King
/// 176 178 179 179 178 176 3994 3992 3990 3990 3992 3994
/// 178 180 180 180 180 178 3994 3992 3990 3990 3992 3994
/// 179 180 181 181 180 179 3996 3994 3992 3992 3994 3995
/// 179 181 181 181 180 179 3998 3996 3996 3996 3996 3998
/// 178 180 181 180 180 178 4001 4001 4000 4000 4001 4001
/// 176 178 179 179 178 176 4004 4006 4002 4002 4006 4004
/// All entries in the figure above are in decimal representation.
///
/// Each entry in the pawn's, bishop's, knight's, and rook's PSTs uses 7 bits, and each entry in
/// the queen's and king's PSTs uses 12 bits. Additionally, each piece is valued as following:
/// | Type | Value |
/// | ------ | ----- |
/// | Pawn | 20 |
/// | Bishop | 66 |
/// | Knight | 64 |
/// | Rook | 100 |
/// | Queen | 180 |
/// | King | 4000 |
/// The king's value just has to be sufficiently larger than 180 * 7 = 1260 (i.e. equivalent to
/// 7 queens) because check/checkmates are detected lazily (see {Engine-generateMoves}).
///
/// The evaluation of a move is given by
/// Δ(PST value of the moved piece) + (PST value of any captured pieces).
/// @param _board The board to apply the move to.
/// @param _move The move to evaluate.
/// @return The evaluation of the move applied to the given position.
function evaluateMove(uint256 _board, uint256 _move) internal pure returns (int256) {
unchecked {
uint256 fromIndex = 6 * (_move >> 9) + ((_move >> 6) & 7) - 7;
uint256 toIndex = 6 * ((_move & 0x3F) >> 3) + ((_move & 0x3F) & 7) - 7;
uint256 pieceAtFromIndex = (_board >> ((_move >> 6) << 2)) & 7;
uint256 pieceAtToIndex = (_board >> ((_move & 0x3F) << 2)) & 7;
uint256 oldPst;
uint256 newPst;
uint256 captureValue;
if (pieceAtToIndex != 0) {
if (pieceAtToIndex < 5) { // Piece is not a queen or king
captureValue = (getPst(pieceAtToIndex) >> (7 * (0x23 - toIndex))) & 0x7F;
} else if (toIndex < 0x12) { // Piece is queen or king and in the closer half
captureValue = (getPst(pieceAtToIndex) >> (0xC * (0x11 - toIndex))) & 0xFFF;
} else { // Piece is queen or king and in the further half
captureValue = (getPstTwo(pieceAtToIndex) >> (0xC * (0x23 - toIndex))) & 0xFFF;
}
}
if (pieceAtFromIndex < 5) { // Piece is not a queen or king
oldPst = (getPst(pieceAtFromIndex) >> (7 * fromIndex)) & 0x7F;
newPst = (getPst(pieceAtFromIndex) >> (7 * toIndex)) & 0x7F;
} else if (fromIndex < 0x12) { // Piece is queen or king and in the closer half
oldPst = (getPstTwo(pieceAtFromIndex) >> (0xC * fromIndex)) & 0xFFF;
newPst = (getPstTwo(pieceAtFromIndex) >> (0xC * toIndex)) & 0xFFF;
} else { // Piece is queen or king and in the further half
oldPst = (getPst(pieceAtFromIndex) >> (0xC * (fromIndex - 0x12))) & 0xFFF;
newPst = (getPst(pieceAtFromIndex) >> (0xC * (toIndex - 0x12))) & 0xFFF;
}
return int256(captureValue + newPst) - int256(oldPst);
}
}
/// @notice Maps a given piece type to its PST (see {Engine-evaluateMove} for details on the
/// PSTs and {Chess} for piece representation).
/// @dev The queen's and king's PSTs do not fit in 1 uint256, so their PSTs are split into 2
/// uint256s each. {Chess-getPst} contains the first half, and {Chess-getPstTwo} contains the
/// second half.
/// @param _type A piece type defined in {Chess}.
/// @return The PST corresponding to `_type`.
function getPst(uint256 _type) internal pure returns (uint256) {
if (_type == 1) return 0x2850A142850F1E3C78F1E2858C182C50A943468A152A788103C54A142850A14;
if (_type == 2) return 0x7D0204080FA042850A140810E24487020448912240810E1428701F40810203E;
if (_type == 3) return 0xC993264C9932E6CD9B365C793264C98F1E4C993263C793264C98F264CB97264;
if (_type == 4) return 0x6CE1B3670E9C3C8101E38750224480E9D4189120BA70F20C178E1B3874E9C36;
if (_type == 5) return 0xB00B20B30B30B20B00B20B40B40B40B40B20B30B40B50B50B40B3;
return 0xF9AF98F96F96F98F9AF9AF98F96F96F98F9AF9CF9AF98F98F9AF9B;
}
/// @notice Maps a queen or king to the second half of its PST (see {Engine-getPst}).
/// @param _type A piece type defined in {Chess}. Must be a queen or a king (see
/// {Engine-getPst}).
/// @return The PST corresponding to `_type`.
function getPstTwo(uint256 _type) internal pure returns (uint256) {
return _type == 5
? 0xB30B50B50B50B40B30B20B40B50B40B40B20B00B20B30B30B20B0
: 0xF9EF9CF9CF9CF9CF9EFA1FA1FA0FA0FA1FA1FA4FA6FA2FA2FA6FA4;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/Strings.sol";
import { Chess } from "./Chess.sol";
import { Base64 } from "./Base64.sol";
/// @title A library that generates HTML art for fiveoutofnine (an on-chain 6x6 chess engine)
/// @author fiveoutofnine
/// @notice Below details how the metadata and art are generated:
/// ==============================================Name==============================================
/// Expressed as Python3 f-strings below, token names generate as
/// ``f"fiveoutofnine - Game #{game_id}, Move #{move_id}"''.
/// ==========================================Description===========================================
/// Token descriptions describe white's move in algebraic notation and black's move in algebraic
/// notation. If white's move results in checkmating black or a stalemate, the description will say
/// black resigned (for simplicity, stalemates are treated as checkmates). Since the engine always
/// plays black, and the player always plays white, white is indicated as ``Player'', and black is
/// indicated as ``fiveoutofnine''. Additionally, for every non game-ending turn, a string graphic
/// is generated after the moves' descriptions. An example:
/// Player plays e4 rook captures e5 queen.
/// 6 · · ♜ · ♚ ♜
/// 5 · ♟ · · ♖ ♟
/// 4 ♟ ♙ ♟ ♙ * ♙
/// 3 ♙ · ♙ · · ·
/// 2 · · · · ♖ ·
/// 1 · ♘ · ♔ · ·
/// a b c d e f
///
/// fiveoutofnine resigns.
/// * indicates the square the piece moved from.
/// ==============================================Art===============================================
/// The art is generated as HTML code with in-line CSS (0 JS) according to the following table:
/// | Property | Name | Value/Description | Determination |
/// | ============== | ========= | ======================================= | =================== |
/// | Dimension | 1 × 1 | 1 × 1 pillars | Player moved king |
/// | (6 traits) | 2 × 2 | 2 × 2 pillars | Player moved rook |
/// | | 3 × 3 | 3 × 3 pillars | Engine moved bishop |
/// | | 4 × 4 | 4 × 4 pillars | Player moved knight |
/// | | 6 × 6 | 6 × 6 pillars | Player moved pawn |
/// | | 12 × 12 | 12 × 12 pillars | Player moved queen |
/// | -------------- | --------- | --------------------------------------- | ------------------- |
/// | Height | Plane | 8px pillar height | 1 / 64 chance[^0] |
/// | (5 traits) | 1/4 | 98px pillar height | 10 / 64 chance[^0] |
/// | | 1/2 | 197px pillar height | 10 / 64 chance[^0] |
/// | | Cube | 394px pillar height | 40 / 64 chance[^0] |
/// | | Infinite | 1000px pillar height | 3 / 64 chance[^0] |
/// | -------------- | --------- | --------------------------------------- | ------------------- |
/// | Gap[^1] | None | 0px gap between the pillars | 4 / 16 chance[^0] |
/// | (4 traits) | Narrow | 2px gap between the pillars | 9 / 16 chance[^0] |
/// | | Wide | 12px gap between the pillars | 2 / 16 chance[^0] |
/// | | Ultrawide | 24px gap between the pillars | 1 / 16 chance[^0] |
/// | -------------- | --------- | --------------------------------------- | ------------------- |
/// | Color | Uniform | All faces are the same color | 7 / 32 chance[^0] |
/// | Generation[^2] | Shades | Faces get darker anticlockwise | 7 / 32 chance[^0] |
/// | (6 traits) | Tints | Faces get lighter anticlockwise | 7 / 32 chance[^0] |
/// | | Eclipse | Left face is white; black face is black | 3 / 32 chance[^0] |
/// | | Void | Left and right face are black | 1 / 32 chance[^0] |
/// | | Curated | One of 8 color themes (see below) | 7 / 32 chance[^0] |
/// | -------------- | --------- | --------------------------------------- | ------------------- |
/// | Color | Nord | 0x8FBCBBEBCB8BD087705E81ACB48EAD | 1 / 8 chance[^0] |
/// | Theme[^3] | B/W | 0x000000FFFFFFFFFFFFFFFFFF000000 | 1 / 8 chance[^0] |
/// | (8 traits) | Candycorn | 0x0D3B66F4D35EEE964BFAF0CAF95738 | 1 / 8 chance[^0] |
/// | | RGB | 0xFFFF0000FF000000FFFF0000FFFF00 | 1 / 8 chance[^0] |
/// | | VSCode | 0x1E1E1E569CD6D2D1A2BA7FB54DC4AC | 1 / 8 chance[^0] |
/// | | Neon | 0x00FFFFFFFF000000FF00FF00FF00FF | 1 / 8 chance[^0] |
/// | | Jungle | 0xBE3400015045020D22EABAACBE3400 | 1 / 8 chance[^0] |
/// | | Corn | 0xF9C233705860211A28346830F9C233 | 1 / 8 chance[^0] |
/// | -------------- | --------- | --------------------------------------- | ------------------- |
/// | Bit Border[^4] | True | The bits have a 1px solid black border | Any pieces captured |
/// | (2 traits) | False | The bits don't have any border | No pieces captuered |
/// | ============== | ========= | ======================================= | =================== |
/// | [^0]: Determined from `_seed`. |
/// | [^1]: Gap is omitted when dimension is 1 x 1. |
/// | [^2]: The first 5 color generation traits are algorithms. A base color is generated from |
/// | `seed`, and the remaining colors are generated according to the selected algorithm. The |
/// | color of the bits is always the complement of the randomly generated base color, and the |
/// | background color depends on the algorithm: |
/// | * Uniform: same as the base color; |
/// | * Shades: darkest shade of the base color; |
/// | * Tints: lightest shade of the base color; |
/// | * Eclipse: same as the base color; |
/// | * Void: complement of the base color. |
/// | If the selected color generation trait is "Curated," 1 of 8 pre-curated themes is randomly |
/// | selected. |
/// | [^3]: The entries in the 3rd column are bitpacked integers where |
/// | * the first 24 bits represent the background color, |
/// | * the second 24 bits represent the left face's color, |
/// | * the third 24 bits represent the right face's color, |
/// | * the fourth 24 bits represent the top face's color, |
/// | * and the last 24 bits represent the bits' color. |
/// | [^4]: Bit border is omitted when dimension is 12 x 12. |
library fiveoutofnineART {
using Strings for uint256;
using Chess for uint256;
string internal constant SVG_STYLES = "--n:calc((394px - (var(--b) - 1)*var(--c))/var(--b));--o"
":calc(106px + var(--n));--p:calc(var(--a)/2)}section{height:var(--a);width:var(--a);backgr"
"ound:var(--e);position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden}.c{height:0;"
"width:0;position:absolute;transition:0.25s}.c:hover{transform:translate(0px,-64px);transit"
"ion:0.25s}.c>*{height:var(--n);width:var(--n);border-bottom:4px solid black;border-right:4"
"px solid black;border-left:1px solid black;border-top:1px solid black;transform-origin:0 0"
";position:relative;box-sizing:border-box}.c>*:nth-child(1){width:var(--d);background-color"
":var(--f);transform:rotate(90deg)skewX(-30deg)scaleY(0.864)}.c>*:nth-child(2){height:var(-"
"-d);bottom:var(--n);background-color:var(--g);transform:rotate(-30deg)skewX(-30deg)scaleY("
"0.864)}#h{background-color:var(--h)}#i{background-color:var(--i)}.c>*:nth-child(3){bottom:"
"calc(var(--d) + var(--n));background-color:var(--h);display:grid;grid-template-columns:rep"
"eat(";
bytes32 internal constant HEXADECIMAL_DIGITS = "0123456789ABCDEF";
bytes32 internal constant FILE_NAMES = "abcdef";
/// @notice Takes in data for a given fiveoutofnine NFT and outputs its metadata in JSON form.
/// Refer to {fiveoutofnineART} for details.
/// @dev The output is base 64-encoded.
/// @param _internalId A bitpacked uint256 where the first 128 bits are the game ID, and the
/// last 128 bits are the move ID within the game.
/// @param _move A struct with information about the player's move and engine's response (see
/// {Chess-Move}).
/// @return Base 64-encoded JSON of metadata generated from `_internalId` and `_move`.
function getMetadata(uint256 _internalId, Chess.Move memory _move)
internal pure
returns (string memory)
{
string memory description;
string memory image;
string memory attributes;
uint256 whiteMove;
uint256 blackMove;
uint256 boardAfterWhiteMove;
uint256 boardAfterBlackMove;
bool whiteCaptures;
bool blackCaptures;
uint256 depth;
{
whiteMove = (_move.metadata >> 0xC) & 0xFFF;
blackMove = _move.metadata & 0xFFF;
boardAfterWhiteMove = _move.board.applyMove(whiteMove);
boardAfterBlackMove = boardAfterWhiteMove.applyMove(blackMove);
whiteCaptures = _move.board.isCapture(
_move.board >> ((whiteMove & 0x3F) << 2)
);
blackCaptures = boardAfterWhiteMove.isCapture(
boardAfterWhiteMove >> ((blackMove & 0x3F) << 2)
);
depth = _move.metadata >> 0x18;
}
{
uint256 numSquares;
{
uint256 whitePieceType = (_move.board >> ((whiteMove >> 6) << 2)) & 7;
uint256 blackPieceType = (boardAfterWhiteMove >> ((blackMove >> 6) << 2)) & 7;
if (whitePieceType == 1) numSquares = 6;
else if (whitePieceType == 3) numSquares = 2;
else if (whitePieceType == 4) numSquares = 4;
else if (whitePieceType == 5) numSquares = 12;
else numSquares = 1;
if (blackPieceType == 2) numSquares = 3;
}
uint256 seed = uint256(
keccak256(abi.encodePacked(_internalId, boardAfterBlackMove, _move.metadata))
);
(image, attributes) = getImage(
boardAfterBlackMove,
numSquares,
seed,
whiteCaptures || blackCaptures
);
}
// Lots of unusual identation and braces to get around the 16 local variable limitation.
{
description = string(
abi.encodePacked(
"---\\n\\n**Player** plays **`",
indexToPosition(whiteMove >> 6, true),
"` ",
getPieceName((_move.board >> ((whiteMove >> 6) << 2)) & 7),
"**",
whiteCaptures
? " captures "
: " to ",
"**`",
indexToPosition(whiteMove & 0x3F, true)
)
);
}
{
description = string(
abi.encodePacked(
description,
"`",
whiteCaptures
? " "
: "",
whiteCaptures
? getPieceName((_move.board >> ((whiteMove & 0x3F) << 2)) & 7)
: "",
"**.\\n\\n",
drawMove(boardAfterWhiteMove, whiteMove >> 6),
"\\n\\n---\\n\\n**fiveoutofnine** "
)
);
}
{
if (blackMove == 0) {
description = string(abi.encodePacked(description, "**resigns**."));
} else {
description = string(
abi.encodePacked(
description,
"responds with **`",
indexToPosition(blackMove >> 6, false),
"` ",
getPieceName((boardAfterWhiteMove >> ((blackMove >> 6) << 2)) & 7),
"**",
blackCaptures
? " captures "
: " to ",
"**`",
indexToPosition(blackMove & 0x3F, false),
"`",
blackCaptures
? " "
: "",
blackCaptures
? getPieceName((boardAfterWhiteMove>> ((blackMove & 0x3F) << 2)) & 7)
: "",
"**.\\n\\n",
drawMove(boardAfterBlackMove, blackMove >> 6)
)
);
}
}
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
abi.encodePacked(
'{"name":"Game #',
Strings.toString(_internalId >> 0x80),
", Move #",
Strings.toString(uint128(_internalId)),
'",'
'"description":"',
description,
'","animation_url":"data:text/html;base64,',
image,
'","attributes":[{"trait_type":"Depth","value":',
depth.toString(),
"},",
attributes,
"]}"
)
)
)
);
}
/// @notice Generates the HTML image and its attributes for a given board/seed according to the
/// table described in {fiveoutofnineART}.
/// @dev The output of the image is base 64-encoded.
/// @param _board The board after the player's and engine's move are played.
/// @param _numSquares The dimension of the board.
/// @param _seed A hash of the game ID, move ID, board position, and metadata.
/// @param _pieceCaptured Whether or not any piees were captured.
/// @return Base 64-encoded image (in HTML) and its attributes.
function getImage(uint256 _board, uint256 _numSquares, uint256 _seed, bool _pieceCaptured)
internal pure
returns (string memory, string memory)
{
string memory attributes = string(
abi.encodePacked(
'{"trait_type":"Dimension","value":"',
_numSquares.toString(),
unicode" × ",
_numSquares.toString(),
'"}'
)
);
string memory styles = string(
abi.encodePacked(
"<style>:root{--a:1000px;--b:",
_numSquares.toString(),
";--c:"
)
);
{
string memory tempAttribute;
string memory tempValue = "0";
if (_numSquares != 1) {
if (_seed & 0xF < 4) { (tempAttribute, tempValue) = ("None", "0"); }
else if (_seed & 0xF < 13) { (tempAttribute, tempValue) = ("Narrow", "2"); }
else if (_seed & 0xF < 15) { (tempAttribute, tempValue) = ("Wide", "12"); }
else { (tempAttribute, tempValue) = ("Ultrawide", "24"); }
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Gap","value":"',
tempAttribute,
'"}'
)
);
}
styles = string(abi.encodePacked(styles, tempValue, "px;--d:"));
}
_seed >>= 4;
{
string memory tempAttribute;
string memory tempValue;
if (_seed & 0x3F < 1) { (tempAttribute, tempValue) = ("Plane", "8"); }
else if (_seed & 0x3F < 11) { (tempAttribute, tempValue) = ("1/4", "98"); }
else if (_seed & 0x3F < 21) { (tempAttribute, tempValue) = ("1/2", "197"); }
else if (_seed & 0x3F < 51) { (tempAttribute, tempValue) = ("Cube", "394"); }
else { (tempAttribute, tempValue) = ("Infinite", "1000"); }
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Height","value":"',
tempAttribute,
'"}'
)
);
styles = string(abi.encodePacked(styles, tempValue, "px;"));
}
_seed >>= 6;
{
string memory tempAttribute;
uint256 colorTheme;
if (_seed & 0x1F < 25) {
colorTheme = (_seed >> 5) & 0xFFFFFF;
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Base Color","value":',
colorTheme.toString(),
"}"
)
);
if (_seed & 0x1F < 7) {
tempAttribute = "Uniform";
colorTheme = (colorTheme << 0x60)
| (colorTheme << 0x48)
| (colorTheme << 0x30)
| (colorTheme << 0x18)
| complementColor(colorTheme);
} else if (_seed & 0x1F < 14) {
tempAttribute = "Shades";
colorTheme = (darkenColor(colorTheme, 3) << 0x60)
| (darkenColor(colorTheme, 1) << 0x48)
| (darkenColor(colorTheme, 2) << 0x30)
| (colorTheme << 0x18)
| complementColor(colorTheme);
} else if (_seed & 0x1F < 21) {
tempAttribute = "Tints";
colorTheme = (brightenColor(colorTheme, 3) << 0x60)
| (brightenColor(colorTheme, 1) << 0x48)
| (brightenColor(colorTheme, 2) << 0x30)
| (colorTheme << 0x18)
| complementColor(colorTheme);
} else if (_seed & 0x1F < 24) {
tempAttribute = "Eclipse";
colorTheme = (colorTheme << 0x60)
| (0xFFFFFF << 0x48)
| (colorTheme << 0x18)
| complementColor(colorTheme);
} else {
tempAttribute = "Void";
colorTheme = (complementColor(colorTheme) << 0x60)
| (colorTheme << 0x18)
| complementColor(colorTheme);
}
} else {
tempAttribute = "Curated";
_seed >>= 5;
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Color Theme","value":"',
["Nord", "B/W", "Candycorn", "RGB", "VSCode", "Neon", "Jungle", "Corn"]
[_seed & 7],
'"}'
)
);
colorTheme = [
0x8FBCBBEBCB8BD087705E81ACB48EAD000000FFFFFFFFFFFFFFFFFF000000,
0x0D3B66F4D35EEE964BFAF0CAF95738FFFF0000FF000000FFFF0000FFFF00,
0x1E1E1E569CD6D2D1A2BA7FB54DC4AC00FFFFFFFF000000FF00FF00FF00FF,
0xBE3400015045020D22EABAACBE3400F9C233705860211A28346830F9C233
][(_seed & 7) >> 1];
colorTheme = _seed & 1 == 0
? colorTheme >> 0x78
: colorTheme & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Color Generation","value":"',
tempAttribute,
'"}'
)
);
styles = string(
abi.encodePacked(
styles,
"--e:",
toColorHexString(colorTheme >> 0x60),
";--f:",
toColorHexString((colorTheme >> 0x48) & 0xFFFFFF),
";--g:",
toColorHexString((colorTheme >> 0x30) & 0xFFFFFF),
";--h:",
toColorHexString((colorTheme >> 0x18) & 0xFFFFFF),
";--i:",
toColorHexString(colorTheme & 0xFFFFFF),
";"
)
);
}
{
string memory tempAttribute;
styles = string(
abi.encodePacked(
styles,
SVG_STYLES,
Strings.toString(12 / _numSquares),
",1fr);grid-template-rows:repeat(",
Strings.toString(12 / _numSquares),
",1fr);transform:rotate(210deg)skew(-30deg)scaleY(0.864)}"
)
);
if (_numSquares != 12) {
if (_pieceCaptured) {
tempAttribute = "True";
styles = string(
abi.encodePacked(
styles,
".c>*:nth-child(3)>div{border: 1px solid black}"
)
);
} else {
tempAttribute = "False";
}
attributes = string(
abi.encodePacked(
attributes,
',{"trait_type":"Bit Border","value":"',
tempAttribute,
'"}'
)
);
}
}
unchecked {
for (uint256 i; i < 23; ++i) {
styles = string(
abi.encodePacked(
styles,
".r",
i.toString(),
"{top:calc(var(--o) + ",
i.toString(),
"*(var(--n)/2 + var(--c)))}"
".c",
i.toString(),
"{left:calc(var(--p) ",
i < 11 ? "-" : "+",
" 0.866*",
i < 11 ? (11 - i).toString() : (i - 11).toString(),
"*(var(--n) + var(--c)))}"
)
);
}
string memory image;
for (uint256 row; row < (_numSquares << 1) - 1; ++row) {
uint256 tempCol = row <= _numSquares - 1
? 11 - row
: 11 - ((_numSquares << 1) - 2 - row);
for (
uint256 col = tempCol;
col <= (row <= _numSquares - 1
? tempCol + (row << 1)
: tempCol + (((_numSquares << 1) - 2 - row) << 1));
col = col + 2
) {
image = string(
abi.encodePacked(
image,
getPillarHtml(_board, 12 / _numSquares, row, col)
)
);
}
}
return (
Base64.encode(
abi.encodePacked(
styles,
"</style><section>",
image,
"</section>"
)
),
attributes
);
}
}
/// @notice Returns the HTML for a particular pillar within the image.
/// @param _board The board after the player's and engine's move are played.
/// @param _dim The dimension of the bits within a pillar.
/// @param _row The row index of the pillar.
/// @param _col The column index of the pillar.
/// @return The HTML for the pillar described by the parameters.
function getPillarHtml(uint256 _board, uint256 _dim, uint256 _row, uint256 _col)
internal pure
returns (string memory)
{
string memory pillar = string(
abi.encodePacked(
'<div class="c r',
_row.toString(),
" c",
_col.toString(),
'"><div></div><div></div><div>'
)
);
uint256 x;
uint256 y;
uint256 colOffset;
uint256 rowOffset;
unchecked {
for (
uint256 subRow = _row * _dim + ((_dim - 1) << 1);
subRow >= _row * _dim + (_dim - 1);
--subRow
) {
rowOffset = 0;
uint256 tempSubCol = _col <= 11
? 11 - _dim * (11 - _col) + colOffset
: 11 + _dim * (_col - 11) + colOffset;
for (
uint256 subCol = tempSubCol;
subCol >= tempSubCol + 1 - _dim;
--subCol
) {
x = 11 - ((11 + subCol - (subRow - rowOffset)) >> 1);
y = 16 - ((subCol + subRow - rowOffset) >> 1);
pillar = string(
abi.encodePacked(
pillar,
'<div id="',
(
_board
>> (Chess.getAdjustedIndex(6 * (y >> 1) + (x >> 1)) << 2)
>> (((0xD8 >> ((x & 1) << 2)) >> ((y & 1) << 1)) & 3)
)
& 1 == 0
? "h"
: "i",
'"></div>'
)
);
rowOffset++;
if (subCol == 0) { break; }
}
colOffset++;
if (subRow == 0) { break; }
}
}
return string(abi.encodePacked(pillar, "</div></div>"));
}
/// @notice Draws out a move being played out on a board position as a string with unicode
/// characters to represent pieces. Files and rows are labeled with standard algebraic
/// notation. For example:
/// ```
/// 6 ♜ ♝ ♛ ♚ ♝ ♜
/// 5 ♟ ♟ ♟ ♟ ♟ ♟
/// 4 · · · · · ·
/// 3 · · ♙ · · ·
/// 2 ♙ ♙ * ♙ ♙ ♙
/// 1 ♖ ♘ ♕ ♔ ♘ ♖
/// a b c d e f
/// ```
/// * indicates the square the piece moved from.
/// @param _board The board the move is played on.
/// @param _fromIndex The from index of the move.
/// @return The string showing the move played out on the board.
function drawMove(uint256 _board, uint256 _fromIndex) internal pure returns (string memory) {
string memory boardString = "```\\n";
if (_board & 1 == 0) _board = _board.rotate();
else _fromIndex = ((7 - (_fromIndex >> 3)) << 3) + (7 - (_fromIndex & 7));
for (
uint256 index = 0x24A2CC34E4524D455665A6DC75E8628E4966A6AAECB6EC72CF4D76;
index != 0;
index >>= 6
) {
uint256 indexToDraw = index & 0x3F;
boardString = string(
abi.encodePacked(
boardString,
indexToDraw & 7 == 6
? string(abi.encodePacked(Strings.toString((indexToDraw >> 3)), " "))
: "",
indexToDraw == _fromIndex
? "*"
: getPieceChar((_board >> (indexToDraw << 2)) & 0xF),
indexToDraw & 7 == 1 && indexToDraw != 9
? "\\n"
: indexToDraw != 9
? " "
: ""
)
);
}
boardString = string(
abi.encodePacked(
boardString,
"\\n a b c d e f\\n```"
)
);
return boardString;
}
/// @notice Computes the complement of 24-bit colors.
/// @param _color A 24-bit color.
/// @return The complement of `_color`.
function complementColor(uint256 _color) internal pure returns (uint256) {
unchecked {
return 0xFFFFFF - _color;
}
}
/// @notice Darkens 24-bit colors.
/// @param _color A 24-bit color.
/// @param _num The number of shades to darken by.
/// @return `_color` darkened `_num` times.
function darkenColor(uint256 _color, uint256 _num) internal pure returns (uint256) {
return (((_color >> 0x10) >> _num) << 0x10)
| ((((_color >> 8) & 0xFF) >> _num) << 8)
| ((_color & 0xFF) >> _num);
}
/// @notice Brightens 24-bit colors.
/// @param _color A 24-bit color.
/// @param _num The number of tints to brighten by.
/// @return `_color` brightened `_num` times.
function brightenColor(uint256 _color, uint256 _num) internal pure returns (uint256) {
unchecked {
return ((0xFF - ((0xFF - (_color >> 0x10)) >> _num)) << 0x10)
| ((0xFF - ((0xFF - ((_color >> 8) & 0xFF)) >> _num)) << 8)
| (0xFF - ((0xFF - (_color & 0xFF)) >> _num));
}
}
/// @notice Returns the color hex string of a 24-bit color.
/// @param _integer A 24-bit color.
/// @return The color hex string of `_integer`.
function toColorHexString(uint256 _integer) internal pure returns (string memory) {
return string(
abi.encodePacked(
"#",
HEXADECIMAL_DIGITS[(_integer >> 0x14) & 0xF],
HEXADECIMAL_DIGITS[(_integer >> 0x10) & 0xF],
HEXADECIMAL_DIGITS[(_integer >> 0xC) & 0xF],
HEXADECIMAL_DIGITS[(_integer >> 8) & 0xF],
HEXADECIMAL_DIGITS[(_integer >> 4) & 0xF],
HEXADECIMAL_DIGITS[_integer & 0xF]
)
);
}
/// @notice Maps piece type to its corresponding name.
/// @param _type A piece type defined in {Chess}.
/// @return The name corresponding to `_type`.
function getPieceName(uint256 _type) internal pure returns (string memory) {
if (_type == 1) return "pawn";
else if (_type == 2) return "bishop";
else if (_type == 3) return "rook";
else if (_type == 4) return "knight";
else if (_type == 5) return "queen";
return "king";
}
/// @notice Converts a position's index to algebraic notation.
/// @param _index The index of the position.
/// @param _isWhite Whether the piece is being determined for a white piece or not.
/// @return The algebraic notation of `_index`.
function indexToPosition(uint256 _index, bool _isWhite) internal pure returns (string memory) {
unchecked {
return _isWhite
? string(
abi.encodePacked(
FILE_NAMES[6 - (_index & 7)],
Strings.toString(_index >> 3))
)
: string(
abi.encodePacked(
FILE_NAMES[(_index & 7) - 1],
Strings.toString(7 - (_index >> 3))
)
);
}
}
/// @notice Maps pieces to its corresponding unicode character.
/// @param _piece A piece.
/// @return The unicode character corresponding to `_piece`. It returns ``.'' otherwise.
function getPieceChar(uint256 _piece) internal pure returns (string memory) {
if (_piece == 1) return unicode"♟";
if (_piece == 2) return unicode"♝";
if (_piece == 3) return unicode"♜";
if (_piece == 4) return unicode"♞";
if (_piece == 5) return unicode"♛";
if (_piece == 6) return unicode"♚";
if (_piece == 9) return unicode"♙";
if (_piece == 0xA) return unicode"♗";
if (_piece == 0xB) return unicode"♖";
if (_piece == 0xC) return unicode"♘";
if (_piece == 0xD) return unicode"♕";
if (_piece == 0xE) return unicode"♔";
return unicode"·";
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.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 `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.0 (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.0 (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.0 (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.0 (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.0 (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.9;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678"
"9+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = TABLE;
uint256 encodedLength = ((data.length + 2) / 3) << 2;
string memory result = new string(encodedLength + 0x20);
assembly {
mstore(result, encodedLength)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 0x20)
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore(resultPtr, shl(0xF8, mload(add(tablePtr, and(shr(0x12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(0xF8, mload(add(tablePtr, and(shr(0xC, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(0xF8, mload(add(tablePtr, and(shr(6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(0xF8, mload(add(tablePtr, and(input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(0xF0, 0x3D3D)) }
case 2 { mstore(sub(resultPtr, 1), shl(0xF8, 0x3D)) }
}
return result;
}
} | Returns the HTML for a particular pillar within the image. _board The board after the player's and engine's move are played. _dim The dimension of the bits within a pillar. _row The row index of the pillar. _col The column index of the pillar. return The HTML for the pillar described by the parameters. | function getPillarHtml(uint256 _board, uint256 _dim, uint256 _row, uint256 _col)
internal pure
returns (string memory)
{
string memory pillar = string(
abi.encodePacked(
'<div class="c r',
_row.toString(),
" c",
_col.toString(),
'"><div></div><div></div><div>'
)
);
uint256 x;
uint256 y;
uint256 colOffset;
uint256 rowOffset;
unchecked {
for (
uint256 subRow = _row * _dim + ((_dim - 1) << 1);
subRow >= _row * _dim + (_dim - 1);
--subRow
) {
rowOffset = 0;
uint256 tempSubCol = _col <= 11
? 11 - _dim * (11 - _col) + colOffset
: 11 + _dim * (_col - 11) + colOffset;
for (
uint256 subCol = tempSubCol;
subCol >= tempSubCol + 1 - _dim;
--subCol
) {
x = 11 - ((11 + subCol - (subRow - rowOffset)) >> 1);
y = 16 - ((subCol + subRow - rowOffset) >> 1);
pillar = string(
abi.encodePacked(
pillar,
'<div id="',
(
_board
>> (Chess.getAdjustedIndex(6 * (y >> 1) + (x >> 1)) << 2)
>> (((0xD8 >> ((x & 1) << 2)) >> ((y & 1) << 1)) & 3)
)
& 1 == 0
? "h"
: "i",
'"></div>'
)
);
rowOffset++;
}
colOffset++;
}
}
return string(abi.encodePacked(pillar, "</div></div>"));
}
| 454,538 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
/**
* @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);
}
interface IPopsicleV3Optimizer {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @return The address of the Uniswap V3 Pool
function pool() external view returns (IUniswapV3Pool);
/// @notice The lower tick of the range
function tickLower() external view returns (int24);
/// @notice The upper tick of the range
function tickUpper() external view returns (int24);
/**
* @notice Deposits tokens in proportion to the Optimizer's current ticks.
* @param amount0Desired Max amount of token0 to deposit
* @param amount1Desired Max amount of token1 to deposit
* @param to address that plp should be transfered
* @return shares minted
* @return amount0 Amount of token0 deposited
* @return amount1 Amount of token1 deposited
*/
function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
/**
* @notice Withdraws tokens in proportion to the Optimizer's holdings.
* @dev Removes proportional amount of liquidity from Uniswap.
* @param shares burned by sender
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1);
/**
* @notice Updates Optimizer's positions.
* @dev Finds base position and limit position for imbalanced token
* mints all amounts to this position(including earned fees)
*/
function rerange() external;
/**
* @notice Updates Optimizer's positions. Can only be called by the governance.
* @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if
* we don't have balance during swap because of price impact.
* mints all amounts to this position(including earned fees)
*/
function rebalance() external;
}
interface IOptimizerStrategy {
/// @return Maximul PLP value that could be minted
function maxTotalSupply() external view returns (uint256);
/// @notice Period of time that we observe for price slippage
/// @return time in seconds
function twapDuration() external view returns (uint32);
/// @notice Maximum deviation of time waited avarage price in ticks
function maxTwapDeviation() external view returns (int24);
/// @notice Tick multuplier for base range calculation
function tickRangeMultiplier() external view returns (int24);
/// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6
/// @return The max price impact percentage
function priceImpactPercentage() external view returns (uint24);
}
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
/// @title Liquidity and ticks functions
/// @notice Provides functions for computing liquidity and ticks for token amounts and prices
library PoolVariables {
using LowGasSafeMath for uint256;
using LowGasSafeMath for uint128;
// Cache struct for calculations
struct Info {
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0;
uint256 amount1;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
/// @param pool Uniswap V3 pool
/// @param liquidity The liquidity being valued
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amounts of token0 and token1 that corresponds to liquidity
function amountsForLiquidity(
IUniswapV3Pool pool,
uint128 liquidity,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint256, uint256) {
//Get current price from the pool
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
/// @param pool Uniswap V3 pool
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return The maximum amount of liquidity that can be held amount0 and amount1
function liquidityForAmounts(
IUniswapV3Pool pool,
uint256 amount0,
uint256 amount1,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint128) {
//Get current price from the pool
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
amount0,
amount1
);
}
/// @dev Amounts of token0 and token1 held in contract position.
/// @param pool Uniswap V3 pool
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amount0 The amount of token0 held in position
/// @return amount1 The amount of token1 held in position
function usersAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper)
internal
view
returns (uint256 amount0, uint256 amount1)
{
//Compute position key
bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
//Get Position.Info for specified ticks
(uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) =
pool.positions(positionKey);
// Calc amounts of token0 and token1 including fees
(amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper);
amount0 = amount0.add(tokensOwed0);
amount1 = amount1.add(tokensOwed1);
}
/// @dev Amount of liquidity in contract position.
/// @param pool Uniswap V3 pool
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return liquidity stored in position
function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper)
internal
view
returns (uint128 liquidity)
{
//Compute position key
bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
//Get liquidity stored in position
(liquidity, , , , ) = pool.positions(positionKey);
}
/// @dev Common checks for valid tick inputs.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
function checkRange(int24 tickLower, int24 tickUpper) internal pure {
require(tickLower < tickUpper, "TLU");
require(tickLower >= TickMath.MIN_TICK, "TLM");
require(tickUpper <= TickMath.MAX_TICK, "TUM");
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
/// @dev Gets ticks with proportion equivalent to desired amount
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param baseThreshold The range for upper and lower ticks
/// @param tickSpacing The pool tick spacing
/// @return tickLower The lower tick of the range
/// @return tickUpper The upper tick of the range
function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) {
Info memory cache =
Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0);
// Get current price and tick from the pool
( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0();
//Calc base ticks
(cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing);
//Calc amounts of token0 and token1 that can be stored in base range
(cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper);
//Liquidity that can be stored in base range
cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper);
//Get imbalanced token
bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1);
//Calc new tick(upper or lower) for imbalanced token
if ( zeroGreaterOne) {
uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false);
cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing);
}
else{
uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false);
cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing);
}
checkRange(cache.tickLower, cache.tickUpper);
tickLower = cache.tickLower;
tickUpper = cache.tickUpper;
}
/// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amount0 amounts of token0 that can be stored in range
/// @return amount1 amounts of token1 that can be stored in range
function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) {
uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper);
(amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper);
}
/// @dev Calc base ticks depending on base threshold and tickspacing
function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) {
int24 tickFloor = floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
}
/// @dev Get imbalanced token
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param amount0 Amounts of token0 that can be stored in base range
/// @param amount1 Amounts of token1 that can be stored in base range
/// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced
function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) {
zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false;
}
// Check price has not moved a lot recently. This mitigates price
// manipulation during rebalance and also prevents placing orders
// when it's too volatile.
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view {
(, int24 currentTick, , , , , ) = pool.slot0();
int24 twap = getTwap(pool, twapDuration);
int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick;
require(deviation <= maxTwapDeviation, "PSC");
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration
function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
}
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
}
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
}
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
}
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions
{
}
/// @title This library is created to conduct a variety of burn liquidity methods
library PoolActions {
using PoolVariables for IUniswapV3Pool;
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/**
* @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply.
* @param pool Uniswap V3 pool
* @param tickLower The lower tick of the range
* @param tickUpper The upper tick of the range
* @param totalSupply The amount of total shares in existence
* @param share to burn
* @param to Recipient of amounts
* @return amount0 Amount of token0 withdrawed
* @return amount1 Amount of token1 withdrawed
*/
function burnLiquidityShare(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint256 totalSupply,
uint256 share,
address to
) internal returns (uint256 amount0, uint256 amount1) {
require(totalSupply > 0, "TS");
uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper);
uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply;
if (liquidity > 0) {
(amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128());
if (amount0 > 0 || amount1 > 0) {
// collect liquidity share
(amount0, amount1) = pool.collect(
to,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
}
}
}
/**
* @notice Withdraws all liquidity in a range from Uniswap pool
* @param pool Uniswap V3 pool
* @param tickLower The lower tick of the range
* @param tickUpper The upper tick of the range
*/
function burnAllLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper
) internal {
// Burn all liquidity in this range
uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
}
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {LowGasSafeMAth}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using LowGasSafeMath for uint256;
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 {
// The {LowGasSafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
}
/// @title Function for getting the current chain ID
library ChainId {
/// @dev Gets the current chain ID
/// @return chainId The current chain ID
function get() internal pure returns (uint256 chainId) {
assembly {
chainId := chainid()
}
}
}
/**
* @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 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) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ISS");
require(v == 27 || v == 28, "ISV");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "IS");
return signer;
}
/**
* @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));
}
}
/**
* @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 = ChainId.get();
_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 (ChainId.get() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
ChainId.get(),
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);
}
}
/**
* @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);
}
/*
* @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;
}
}
/**
* @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 LowGasSafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "TEA"));
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, "DEB"));
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), "FZA");
require(recipient != address(0), "TZA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TEB");
_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), "MZA");
_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), "BZA");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BEB");
_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), "AFZA");
require(spender != address(0), "ATZA");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @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;
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @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 {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ED");
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, "IS");
_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.
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Returns floor(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, floor(x / y)
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := div(x, y)
}
}
}
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) {
require((z = x - y) <= x, errorMessage);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/// @notice Returns x + y, reverts if sum overflows uint128
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if sum overflows uint128
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require(x == 0 || (z = x * y) / x == y);
}
}
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
}
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
}
/**
* @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, "RC");
// 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;
}
}
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
}
/// @title PopsicleV3 Optimizer is a yield enchancement v3 contract
/// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as
/// intermediary between the user who wants to provide liquidity to specific pools
/// and earn fees from such actions. The contract ensures that user position is in
/// range and earns maximum amount of fees available at current liquidity utilization
/// rate.
contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer {
using LowGasSafeMath for uint256;
using LowGasSafeMath for uint160;
using LowGasSafeMath for uint128;
using UnsafeMath for uint256;
using SafeCast for uint256;
using PoolVariables for IUniswapV3Pool;
using PoolActions for IUniswapV3Pool;
//Any data passed through by the caller via the IUniswapV3PoolActions#mint call
struct MintCallbackData {
address payer;
}
//Any data passed through by the caller via the IUniswapV3PoolActions#swap call
struct SwapCallbackData {
bool zeroForOne;
}
/// @notice Emitted when user adds liquidity
/// @param sender The address that minted the liquidity
/// @param share The amount of share of liquidity added by the user to position
/// @param amount0 How much token0 was required for the added liquidity
/// @param amount1 How much token1 was required for the added liquidity
event Deposit(
address indexed sender,
uint256 share,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when user withdraws liquidity
/// @param sender The address that minted the liquidity
/// @param shares of liquidity withdrawn by the user from the position
/// @param amount0 How much token0 was required for the added liquidity
/// @param amount1 How much token1 was required for the added liquidity
event Withdraw(
address indexed sender,
uint256 shares,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees was collected from the pool
/// @param feesFromPool0 Total amount of fees collected in terms of token 0
/// @param feesFromPool1 Total amount of fees collected in terms of token 1
/// @param usersFees0 Total amount of fees collected by users in terms of token 0
/// @param usersFees1 Total amount of fees collected by users in terms of token 1
event CollectFees(
uint256 feesFromPool0,
uint256 feesFromPool1,
uint256 usersFees0,
uint256 usersFees1
);
/// @notice Emitted when fees was compuonded to the pool
/// @param amount0 Total amount of fees compounded in terms of token 0
/// @param amount1 Total amount of fees compounded in terms of token 1
event CompoundFees(
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool
/// @param tickLower Lower price tick of the positon
/// @param tickUpper Upper price tick of the position
/// @param amount0 Amount of token 0 deposited to the position
/// @param amount1 Amount of token 1 deposited to the position
event Rerange(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when user collects his fee share
/// @param sender User address
/// @param fees0 Exact amount of fees claimed by the users in terms of token 0
/// @param fees1 Exact amount of fees claimed by the users in terms of token 1
event RewardPaid(
address indexed sender,
uint256 fees0,
uint256 fees1
);
/// @notice Shows current Optimizer's balances
/// @param totalAmount0 Current token0 Optimizer's balance
/// @param totalAmount1 Current token1 Optimizer's balance
event Snapshot(uint256 totalAmount0, uint256 totalAmount1);
event TransferGovernance(address indexed previousGovernance, address indexed newGovernance);
/// @notice Prevents calls from users
modifier onlyGovernance {
require(msg.sender == governance, "OG");
_;
}
/// @inheritdoc IPopsicleV3Optimizer
address public immutable override token0;
/// @inheritdoc IPopsicleV3Optimizer
address public immutable override token1;
// WETH address
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// @inheritdoc IPopsicleV3Optimizer
int24 public immutable override tickSpacing;
uint constant MULTIPLIER = 1e6;
uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%)
//The protocol's fee in hundredths of a bip, i.e. 1e-6
uint24 constant protocolFee = 1e5;
mapping (address => bool) private _operatorApproved;
// @inheritdoc IPopsicleV3Optimizer
IUniswapV3Pool public override pool;
// Accrued protocol fees in terms of token0
uint256 public protocolFees0;
// Accrued protocol fees in terms of token1
uint256 public protocolFees1;
// Total lifetime accrued fees in terms of token0
uint256 public totalFees0;
// Total lifetime accrued fees in terms of token1
uint256 public totalFees1;
// Address of the Optimizer's owner
address public governance;
// Pending to claim ownership address
address public pendingGovernance;
//PopsicleV3 Optimizer settings address
address public strategy;
// Current tick lower of Optimizer pool position
int24 public override tickLower;
// Current tick higher of Optimizer pool position
int24 public override tickUpper;
// Checks if Optimizer is initialized
bool public initialized;
bool private _paused = false;
/**
* @dev After deploying, strategy can be set via `setStrategy()`
* @param _pool Underlying Uniswap V3 pool with fee = 3000
* @param _strategy Underlying Optimizer Strategy for Optimizer settings
*/
constructor(
address _pool,
address _strategy
) ERC20("Popsicle LP V3 USDC/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDC/WETH") {
pool = IUniswapV3Pool(_pool);
strategy = _strategy;
token0 = pool.token0();
token1 = pool.token1();
tickSpacing = pool.tickSpacing();
governance = msg.sender;
_operatorApproved[msg.sender] = true;
}
//initialize strategy
function init() external onlyGovernance {
require(!initialized, "F");
initialized = true;
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
( , int24 currentTick, , , , , ) = pool.slot0();
int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow
}
/// @inheritdoc IPopsicleV3Optimizer
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
)
external
override
nonReentrant
checkDeviation
whenNotPaused
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 && amount1Desired > 0, "ANV");
_earnFees();
_compoundFees(); // prevent user drains others
uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper);
// compute the liquidity amount
uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper);
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: msg.sender})));
shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER);
_mint(to, shares);
require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS");
emit Deposit(msg.sender, shares, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function withdraw(
uint256 shares,
address to
)
external
override
nonReentrant
checkDeviation
whenNotPaused
returns (
uint256 amount0,
uint256 amount1
)
{
require(shares > 0, "S");
require(to != address(0), "WZA");
_earnFees();
_compoundFees();
(amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to);
require(amount0 > 0 || amount1 > 0, "EA");
// Burn shares
_burn(msg.sender, shares);
emit Withdraw(msg.sender, shares, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function rerange() external override nonReentrant checkDeviation {
require(_operatorApproved[msg.sender], "ONA");
_earnFees();
//Burn all liquidity from pool to rerange for Optimizer's balances.
pool.burnAllLiquidity(tickLower, tickUpper);
// Emit snapshot to record balances
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
emit Snapshot(balance0, balance1);
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
//Get exact ticks depending on Optimizer's balances
(tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing);
//Get Liquidity for Optimizer's balances
uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
// Add liquidity to the pool
(uint256 amount0, uint256 amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit Rerange(tickLower, tickUpper, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function rebalance() external override nonReentrant checkDeviation {
require(_operatorApproved[msg.sender], "ONA");
_earnFees();
//Burn all liquidity from pool to rerange for Optimizer's balances.
pool.burnAllLiquidity(tickLower, tickUpper);
//Calc base ticks
(uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0();
PoolVariables.Info memory cache;
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
(cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing);
cache.amount0Desired = _balance0();
cache.amount1Desired = _balance1();
emit Snapshot(cache.amount0Desired, cache.amount1Desired);
// Calc liquidity for base ticks
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper);
// Get exact amounts for base ticks
(cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper);
// Get imbalanced token
bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1);
// Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio
int256 amountSpecified =
zeroForOne
? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2))
: int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2
// Calculate Price limit depending on price impact
uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER;
uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact);
//Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit
pool.swap(
address(this),
zeroForOne,
amountSpecified,
sqrtPriceLimitX96,
abi.encode(SwapCallbackData({zeroForOne: zeroForOne}))
);
(sqrtPriceX96, currentTick, , , , , ) = pool.slot0();
// Emit snapshot to record balances
cache.amount0Desired = _balance0();
cache.amount1Desired = _balance1();
emit Snapshot(cache.amount0Desired, cache.amount1Desired);
//Get exact ticks depending on Optimizer's new balances
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing);
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
// Add liquidity to the pool
(cache.amount0, cache.amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
cache.liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1);
}
// Calcs user share depending on deposited amounts
function _calcShare(uint256 liquidity, uint256 liquidityLast)
internal
view
returns (
uint256 shares
)
{
shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast);
}
/// @dev Amount of token0 held as unused balance.
function _balance0() internal view returns (uint256) {
return IERC20(token0).balanceOf(address(this)).sub(protocolFees0);
}
/// @dev Amount of token1 held as unused balance.
function _balance1() internal view returns (uint256) {
return IERC20(token1).balanceOf(address(this)).sub(protocolFees1);
}
/// @dev collects fees from the pool
function _earnFees() internal {
uint liquidity = pool.positionLiquidity(tickLower, tickUpper);
if (liquidity == 0) return; // we can't poke when liquidity is zero
// Do zero-burns to poke the Uniswap pools so earned fees are updated
pool.burn(tickLower, tickUpper, 0);
(uint256 collect0, uint256 collect1) =
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
// Calculate protocol's fees
uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER);
uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER);
protocolFees0 = protocolFees0.add(earnedProtocolFees0);
protocolFees1 = protocolFees1.add(earnedProtocolFees1);
totalFees0 = totalFees0.add(collect0);
totalFees1 = totalFees1.add(collect1);
emit CollectFees(collect0, collect1, totalFees0, totalFees1);
}
function _compoundFees() internal returns (uint256 amount0, uint256 amount1){
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
emit Snapshot(balance0, balance1);
//Get Liquidity for Optimizer's balances
uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
// Add liquidity to the pool
if (liquidity > 0)
{
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit CompoundFees(amount0, amount1);
}
}
/// @notice Returns current Optimizer's position in pool
function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) {
bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @notice Returns current Optimizer's users amounts in pool
function usersAmounts() external view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = pool.usersAmounts(tickLower, tickUpper);
}
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay to the pool for the minted liquidity.
/// @param amount0 The amount of token0 due to the pool for the minted liquidity
/// @param amount1 The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external {
require(msg.sender == address(pool), "FP");
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0);
if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1);
}
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.
/// @dev In the implementation you must pay to the pool for swap.
/// @param amount0 The amount of token0 due to the pool for the swap
/// @param amount1 The amount of token1 due to the pool for the swap
/// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0,
int256 amount1,
bytes calldata _data
) external {
require(msg.sender == address(pool), "FP");
require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
bool zeroForOne = data.zeroForOne;
if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0));
else pay(token1, address(this), msg.sender, uint256(amount1));
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == weth && address(this).balance >= value) {
// pay with WETH9
IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay
IWETH9(weth).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
/**
* @notice Used to withdraw accumulated protocol fees.
*/
function collectProtocolFees(
uint256 amount0,
uint256 amount1
) external nonReentrant onlyGovernance {
_earnFees();
require(protocolFees0 >= amount0, "A0F");
require(protocolFees1 >= amount1, "A1F");
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
require(balance0 >= amount0 && balance1 >= amount1);
if (amount0 > 0) pay(token0, address(this), msg.sender, amount0);
if (amount1 > 0) pay(token1, address(this), msg.sender, amount1);
protocolFees0 = protocolFees0.sub(amount0);
protocolFees1 = protocolFees1.sub(amount1);
_compoundFees();
emit RewardPaid(msg.sender, amount0, amount1);
}
// Function modifier that checks if price has not moved a lot recently.
// This mitigates price manipulation during rebalance and also prevents placing orders
// when it's too volatile.
modifier checkDeviation() {
pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration());
_;
}
/**
* @notice `setGovernance()` should be called by the existing governance
* address prior to calling this function.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice Governance address is not updated until the new governance
* address has called `acceptGovernance()` to accept this responsibility.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "PG");
emit TransferGovernance(governance, pendingGovernance);
pendingGovernance = address(0);
governance = msg.sender;
}
// Sets new strategy contract address for new settings
function setStrategy(address _strategy) external onlyGovernance {
require(_strategy != address(0), "NA");
strategy = _strategy;
}
function approveOperator(address _operator) external onlyGovernance {
_operatorApproved[_operator] = true;
}
function disableOperator(address _operator) external onlyGovernance {
_operatorApproved[_operator] = false;
}
function isOperator(address _operator) external view returns (bool) {
return _operatorApproved[_operator];
}
/**
* @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, "P");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "NP");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() external onlyGovernance whenNotPaused {
_paused = true;
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() external onlyGovernance whenPaused {
_paused = false;
}
} | this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); however that code costs significantly more gas | function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
| 9,358 |
// SPDX-License-Identifier: MIT
/* solhint-disable var-name-mixedcase */
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/ILight.sol";
/**
* @title AirSwap Light: Atomic Swap between Tokens
* @notice https://www.airswap.io/
*/
contract Light is ILight, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 public constant LIGHT_ORDER_TYPEHASH =
keccak256(
abi.encodePacked(
"LightOrder(",
"uint256 nonce,",
"uint256 expiry,",
"address signerWallet,",
"address signerToken,",
"uint256 signerAmount,",
"uint256 signerFee,",
"address senderWallet,",
"address senderToken,",
"uint256 senderAmount",
")"
)
);
bytes32 public constant DOMAIN_NAME = keccak256("SWAP_LIGHT");
bytes32 public constant DOMAIN_VERSION = keccak256("3");
uint256 public immutable DOMAIN_CHAIN_ID;
bytes32 public immutable DOMAIN_SEPARATOR;
uint256 public constant FEE_DIVISOR = 10000;
uint256 public signerFee;
uint256 public conditionalSignerFee;
// size of fixed array that holds max returning error messages
uint256 internal constant MAX_ERROR_COUNT = 6;
/**
* @notice Double mapping of signers to nonce groups to nonce states
* @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key
* @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used
*/
mapping(address => mapping(uint256 => uint256)) internal _nonceGroups;
mapping(address => address) public override authorized;
address public feeWallet;
uint256 public stakingRebateMinimum;
address public stakingToken;
constructor(
address _feeWallet,
uint256 _signerFee,
uint256 _conditionalSignerFee,
uint256 _stakingRebateMinimum,
address _stakingToken
) {
// Ensure the fee wallet is not null
require(_feeWallet != address(0), "INVALID_FEE_WALLET");
// Ensure the fee is less than divisor
require(_signerFee < FEE_DIVISOR, "INVALID_FEE");
// Ensure the conditional fee is less than divisor
require(_conditionalSignerFee < FEE_DIVISOR, "INVALID_CONDITIONAL_FEE");
// Ensure the staking token is not null
require(_stakingToken != address(0), "INVALID_STAKING_TOKEN");
uint256 currentChainId = getChainId();
DOMAIN_CHAIN_ID = currentChainId;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
DOMAIN_NAME,
DOMAIN_VERSION,
currentChainId,
this
)
);
feeWallet = _feeWallet;
signerFee = _signerFee;
conditionalSignerFee = _conditionalSignerFee;
stakingRebateMinimum = _stakingRebateMinimum;
stakingToken = _stakingToken;
}
/**
* @notice Validates Light Order for any potential errors
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
* @param senderWallet address Wallet of the sender
* @return tuple of error count and bytes32[] memory array of error messages
*/
function validate(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s,
address senderWallet
) public view returns (uint256, bytes32[] memory) {
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
OrderDetails memory details;
uint256 errCount;
details.nonce = nonce;
details.expiry = expiry;
details.signerWallet = signerWallet;
details.signerToken = signerToken;
details.signerAmount = signerAmount;
details.senderToken = senderToken;
details.senderAmount = senderAmount;
details.v = v;
details.r = r;
details.s = s;
details.senderWallet = senderWallet;
bytes32 hashed = _getOrderHash(
details.nonce,
details.expiry,
details.signerWallet,
details.signerToken,
details.signerAmount,
details.senderWallet,
details.senderToken,
details.senderAmount
);
address signatory = _getSignatory(hashed, v, r, s);
uint256 swapFee = details.signerAmount.mul(signerFee).div(FEE_DIVISOR);
// Ensure the signatory is not null
if (signatory == address(0)) {
errors[errCount] = "INVALID_SIG";
errCount++;
}
//expiry check
if (details.expiry < block.timestamp) {
errors[errCount] = "EXPIRY_PASSED";
errCount++;
}
//if signatory is not the signerWallet, then it must have been authorized
if (details.signerWallet != signatory) {
if (authorized[details.signerWallet] != signatory) {
errors[errCount] = "UNAUTHORIZED";
errCount++;
}
}
//accounts & balances check
uint256 signerBalance = IERC20(details.signerToken).balanceOf(
details.signerWallet
);
uint256 signerAllowance = IERC20(details.signerToken).allowance(
details.signerWallet,
address(this)
);
if (signerAllowance < details.signerAmount + swapFee) {
errors[errCount] = "SIGNER_ALLOWANCE_LOW";
errCount++;
}
if (signerBalance < details.signerAmount + swapFee) {
errors[errCount] = "SIGNER_BALANCE_LOW";
errCount++;
}
//nonce check
if (nonceUsed(details.signerWallet, details.nonce)) {
errors[errCount] = "NONCE_ALREADY_USED";
errCount++;
}
return (errCount, errors);
}
/**
* @notice Atomic ERC20 Swap
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swap(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
swapWithRecipient(
msg.sender,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
}
/**
* @notice Set the fee wallet
* @param newFeeWallet address Wallet to transfer signerFee to
*/
function setFeeWallet(address newFeeWallet) external onlyOwner {
// Ensure the new fee wallet is not null
require(newFeeWallet != address(0), "INVALID_FEE_WALLET");
feeWallet = newFeeWallet;
emit SetFeeWallet(newFeeWallet);
}
/**
* @notice Set the fee
* @param newSignerFee uint256 Value of the fee in basis points
*/
function setFee(uint256 newSignerFee) external onlyOwner {
// Ensure the fee is less than divisor
require(newSignerFee < FEE_DIVISOR, "INVALID_FEE");
signerFee = newSignerFee;
emit SetFee(newSignerFee);
}
/**
* @notice Set the conditional fee
* @param newConditionalSignerFee uint256 Value of the fee in basis points
*/
function setConditionalFee(uint256 newConditionalSignerFee)
external
onlyOwner
{
// Ensure the fee is less than divisor
require(newConditionalSignerFee < FEE_DIVISOR, "INVALID_FEE");
conditionalSignerFee = newConditionalSignerFee;
emit SetConditionalFee(conditionalSignerFee);
}
/**
* @notice Set the staking token
* @param newStakingToken address Token to check balances on
*/
function setStakingToken(address newStakingToken) external onlyOwner {
// Ensure the new staking token is not null
require(newStakingToken != address(0), "INVALID_FEE_WALLET");
stakingToken = newStakingToken;
emit SetStakingToken(newStakingToken);
}
/**
* @notice Authorize a signer
* @param signer address Wallet of the signer to authorize
* @dev Emits an Authorize event
*/
function authorize(address signer) external override {
authorized[msg.sender] = signer;
emit Authorize(signer, msg.sender);
}
/**
* @notice Revoke authorization of a signer
* @dev Emits a Revoke event
*/
function revoke() external override {
address tmp = authorized[msg.sender];
delete authorized[msg.sender];
emit Revoke(tmp, msg.sender);
}
/**
* @notice Cancel one or more nonces
* @dev Cancelled nonces are marked as used
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
function cancel(uint256[] calldata nonces) external override {
for (uint256 i = 0; i < nonces.length; i++) {
uint256 nonce = nonces[i];
if (_markNonceAsUsed(msg.sender, nonce)) {
emit Cancel(nonce, msg.sender);
}
}
}
/**
* @notice Atomic ERC20 Swap with Recipient
* @param recipient Wallet of the recipient
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapWithRecipient(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount);
// Transfer fee from signer to feeWallet
uint256 feeAmount = signerAmount.mul(signerFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
IERC20(signerToken).safeTransferFrom(signerWallet, feeWallet, feeAmount);
}
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
signerFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Atomic ERC20 Swap with Rebate for Stakers
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapWithConditionalFee(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Transfer fee from signer
uint256 feeAmount = signerAmount.mul(conditionalSignerFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
// Check sender staking balance for rebate
if (IERC20(stakingToken).balanceOf(msg.sender) >= stakingRebateMinimum) {
// Transfer fee from signer to sender
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
feeAmount
);
} else {
// Transfer fee from signer to feeWallet
IERC20(signerToken).safeTransferFrom(
signerWallet,
feeWallet,
feeAmount
);
}
}
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
signerFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Returns true if the nonce has been used
* @param signer address Address of the signer
* @param nonce uint256 Nonce being checked
*/
function nonceUsed(address signer, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;
}
/**
* @notice Returns the current chainId using the chainid opcode
* @return id uint256 The chain id
*/
function getChainId() public view returns (uint256 id) {
// no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Marks a nonce as used for the given signer
* @param signer address Address of the signer for which to mark the nonce as used
* @param nonce uint256 Nonce to be marked as used
* @return bool True if the nonce was not marked as used already
*/
function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
/**
* @notice Checks Order Expiry, Nonce, Signature
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function _checkValidOrder(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 hashed = _getOrderHash(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
msg.sender,
senderToken,
senderAmount
);
// Recover the signatory from the hash and signature
address signatory = _getSignatory(hashed, v, r, s);
// Ensure the signatory is not null
require(signatory != address(0), "INVALID_SIG");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
}
/**
* @notice Hash order parameters
* @param nonce uint256
* @param expiry uint256
* @param signerWallet address
* @param signerToken address
* @param signerAmount uint256
* @param senderToken address
* @param senderAmount uint256
* @return bytes32
*/
function _getOrderHash(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderWallet,
address senderToken,
uint256 senderAmount
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
LIGHT_ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
signerFee,
senderWallet,
senderToken,
senderAmount
)
);
}
/**
* @notice Recover the signatory from a signature
* @param hash bytes32
* @param v uint8
* @param r bytes32
* @param s bytes32
*/
function _getSignatory(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (address) {
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)
);
address signatory = ecrecover(digest, v, r, s);
return signatory;
}
}
| Revoke authorization of a signer Emits a Revoke event/ | function revoke() external override {
address tmp = authorized[msg.sender];
delete authorized[msg.sender];
emit Revoke(tmp, msg.sender);
}
| 996,814 |
./partial_match/1/0xBfCDE0b176D1593edc3cADF4dd5F82770d99aDBE/sources/MoonRabbit.sol | exclude from paying fees or having max transaction amount | constructor() ERC20(unicode"Moon Rabbit",unicode"月の兎") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setpartner(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 7;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 7;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e6 * 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);
| 9,335,321 |
/**
*Submitted for verification at Etherscan.io on 2021-10-19
*/
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: DebtCache.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/DebtCache.sol
* Docs: https://docs.synthetix.io/contracts/DebtCache
*
* Contract Dependencies:
* - BaseDebtCache
* - IAddressResolver
* - IDebtCache
* - MixinResolver
* - MixinSystemSettings
* - Owned
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* 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 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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
/* ---------- Utilities ---------- */
/*
* Absolute value of the input, returned as a signed number.
*/
function signedAbs(int x) internal pure returns (int) {
return x < 0 ? -x : x;
}
/*
* Absolute value of the input, returned as an unsigned number.
*/
function abs(int x) internal pure returns (uint) {
return uint(signedAbs(x));
}
}
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant SETTING_MIN_CRATIO = "minCratio";
bytes32 internal constant SETTING_NEW_COLLATERAL_MANAGER = "newCollateralManager";
bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay";
bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
function getMinCratio(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_MIN_CRATIO, collateral))
);
}
function getNewCollateralManager(address collateral) internal view returns (address) {
return
flexibleStorage().getAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_NEW_COLLATERAL_MANAGER, collateral))
);
}
function getInteractionDelay(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral))
);
}
function getCollapseFeeRate(address collateral) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral))
);
}
}
interface IDebtCache {
// Views
function cachedDebt() external view returns (uint);
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint);
function cacheTimestamp() external view returns (uint);
function cacheInvalid() external view returns (bool);
function cacheStale() external view returns (bool);
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (
uint[] memory debtValues,
uint excludedDebt,
bool anyRateIsInvalid
);
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory debtValues);
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid);
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid);
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
);
// Mutative functions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function purgeCachedSynthDebt(bytes32 currencyKey) external;
function takeDebtSnapshot() external;
function updateCachedsUSDDebt(int amount) external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external;
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isSynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 synth) external view returns (uint amount);
function short(bytes32 synth) external view returns (uint amount);
function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external;
function addShortableSynths(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeShortableSynths(bytes32[] calldata synths) external;
// State mutative
function incrementLongs(bytes32 synth, uint amount) external;
function decrementLongs(bytes32 synth, uint amount) external;
function incrementShorts(bytes32 synth, uint amount) external;
function decrementShorts(bytes32 synth, uint amount) external;
function accrueInterest(
uint interestIndex,
bytes32 currency,
bool isShort
) external returns (uint difference, uint index);
function updateBorrowRatesCollateral(uint rate) external;
function updateShortRatesCollateral(bytes32 currency, uint rate) external;
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// Inheritance
// Libraries
// Internal references
//
// The debt cache (SIP-91) caches the global debt and the debt of each synth in the system.
// Debt is denominated by the synth supply multiplied by its current exchange rate.
//
// The cache can be invalidated when an exchange rate changes, and thereafter must be
// updated by performing a debt snapshot, which recomputes the global debt sum using
// current synth supplies and exchange rates. This is performed usually by a snapshot keeper.
//
// Some synths are backed by non-SNX collateral, such as sETH being backed by ETH
// held in the EtherWrapper (SIP-112). This debt is called "excluded debt" and is
// excluded from the global debt in `_cachedDebt`.
//
// https://docs.synthetix.io/contracts/source/contracts/debtcache
contract BaseDebtCache is Owned, MixinSystemSettings, IDebtCache {
using SafeMath for uint;
using SafeDecimalMath for uint;
uint internal _cachedDebt;
mapping(bytes32 => uint) internal _cachedSynthDebt;
uint internal _cacheTimestamp;
bool internal _cacheInvalid = true;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant sUSD = "sUSD";
bytes32 internal constant sETH = "sETH";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](6);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYSTEMSTATUS;
newAddresses[4] = CONTRACT_COLLATERALMANAGER;
newAddresses[5] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function debtSnapshotStaleTime() external view returns (uint) {
return getDebtSnapshotStaleTime();
}
function cachedDebt() external view returns (uint) {
return _cachedDebt;
}
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) {
return _cachedSynthDebt[currencyKey];
}
function cacheTimestamp() external view returns (uint) {
return _cacheTimestamp;
}
function cacheInvalid() external view returns (bool) {
return _cacheInvalid;
}
function _cacheStale(uint timestamp) internal view returns (bool) {
// Note a 0 timestamp means that the cache is uninitialised.
// We'll keep the check explicitly in case the stale time is
// ever set to something higher than the current unix time (e.g. to turn off staleness).
return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0;
}
function cacheStale() external view returns (bool) {
return _cacheStale(_cacheTimestamp);
}
// Returns the USD-denominated supply of each synth in `currencyKeys`, according to `rates`.
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates)
internal
view
returns (uint[] memory values)
{
uint numValues = currencyKeys.length;
values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return (values);
}
function _currentSynthDebts(bytes32[] memory currencyKeys)
internal
view
returns (
uint[] memory snxIssuedDebts,
uint _excludedDebt,
bool anyRateIsInvalid
)
{
(uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
uint[] memory values = _issuedSynthValues(currencyKeys, rates);
(uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt();
return (values, excludedDebt, isInvalid || isAnyNonSnxDebtRateInvalid);
}
// Returns the USD-denominated supply of each synth in `currencyKeys`, using current exchange rates.
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (
uint[] memory debtValues,
uint excludedDebt,
bool anyRateIsInvalid
)
{
return _currentSynthDebts(currencyKeys);
}
function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) {
uint numKeys = currencyKeys.length;
uint[] memory debts = new uint[](numKeys);
for (uint i = 0; i < numKeys; i++) {
debts[i] = _cachedSynthDebt[currencyKeys[i]];
}
return debts;
}
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) {
return _cachedSynthDebts(currencyKeys);
}
function _totalNonSnxBackedDebt() internal view returns (uint excludedDebt, bool isInvalid) {
// Calculate excluded debt.
// 1. MultiCollateral long debt + short debt.
(uint longValue, bool anyTotalLongRateIsInvalid) = collateralManager().totalLong();
(uint shortValue, bool anyTotalShortRateIsInvalid) = collateralManager().totalShort();
isInvalid = anyTotalLongRateIsInvalid || anyTotalShortRateIsInvalid;
excludedDebt = longValue.add(shortValue);
// 2. EtherWrapper.
// Subtract sETH and sUSD issued by EtherWrapper.
excludedDebt = excludedDebt.add(etherWrapper().totalIssuedSynths());
return (excludedDebt, isInvalid);
}
// Returns the total sUSD debt backed by non-SNX collateral.
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid) {
return _totalNonSnxBackedDebt();
}
function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
// Sum all issued synth values based on their supply.
uint[] memory values = _issuedSynthValues(currencyKeys, rates);
(uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt();
uint numValues = values.length;
uint total;
for (uint i; i < numValues; i++) {
total = total.add(values[i]);
}
total = total < excludedDebt ? 0 : total.sub(excludedDebt);
return (total, isInvalid || isAnyNonSnxDebtRateInvalid);
}
// Returns the current debt of the system, excluding non-SNX backed debt (eg. EtherWrapper).
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) {
return _currentDebt();
}
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
)
{
uint time = _cacheTimestamp;
return (_cachedDebt, time, _cacheInvalid, _cacheStale(time));
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Stub out all mutative functions as no-ops;
// since they do nothing, there are no restrictions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external {}
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external {}
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external {}
function updateDebtCacheValidity(bool currentlyInvalid) external {}
function purgeCachedSynthDebt(bytes32 currencyKey) external {}
function takeDebtSnapshot() external {}
/* ========== MODIFIERS ========== */
function _requireSystemActiveIfNotOwner() internal view {
if (msg.sender != owner) {
systemStatus().requireSystemActive();
}
}
modifier requireSystemActiveIfNotOwner() {
_requireSystemActiveIfNotOwner();
_;
}
function _onlyIssuer() internal view {
require(msg.sender == address(issuer()), "Sender is not Issuer");
}
modifier onlyIssuer() {
_onlyIssuer();
_;
}
function _onlyIssuerOrExchanger() internal view {
require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger");
}
modifier onlyIssuerOrExchanger() {
_onlyIssuerOrExchanger();
_;
}
}
// Libraries
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/debtcache
contract DebtCache is BaseDebtCache {
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "DebtCache";
constructor(address _owner, address _resolver) public BaseDebtCache(_owner, _resolver) {}
bytes32 internal constant EXCLUDED_DEBT_KEY = "EXCLUDED_DEBT";
/* ========== MUTATIVE FUNCTIONS ========== */
// This function exists in case a synth is ever somehow removed without its snapshot being updated.
function purgeCachedSynthDebt(bytes32 currencyKey) external onlyOwner {
require(issuer().synths(currencyKey) == ISynth(0), "Synth exists");
delete _cachedSynthDebt[currencyKey];
}
function takeDebtSnapshot() external requireSystemActiveIfNotOwner {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory values, uint excludedDebt, bool isInvalid) = _currentSynthDebts(currencyKeys);
uint numValues = values.length;
uint snxCollateralDebt;
for (uint i; i < numValues; i++) {
uint value = values[i];
snxCollateralDebt = snxCollateralDebt.add(value);
_cachedSynthDebt[currencyKeys[i]] = value;
}
_cachedSynthDebt[EXCLUDED_DEBT_KEY] = excludedDebt;
uint newDebt = snxCollateralDebt.floorsub(excludedDebt);
_cachedDebt = newDebt;
_cacheTimestamp = block.timestamp;
emit DebtCacheUpdated(newDebt);
emit DebtCacheSnapshotTaken(block.timestamp);
// (in)validate the cache if necessary
_updateDebtCacheValidity(isInvalid);
}
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external requireSystemActiveIfNotOwner {
(uint[] memory rates, bool anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
_updateCachedSynthDebtsWithRates(currencyKeys, rates, anyRateInvalid);
}
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external onlyIssuer {
bytes32[] memory synthKeyArray = new bytes32[](1);
synthKeyArray[0] = currencyKey;
uint[] memory synthRateArray = new uint[](1);
synthRateArray[0] = currencyRate;
_updateCachedSynthDebtsWithRates(synthKeyArray, synthRateArray, false);
}
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates)
external
onlyIssuerOrExchanger
{
_updateCachedSynthDebtsWithRates(currencyKeys, currencyRates, false);
}
function updateDebtCacheValidity(bool currentlyInvalid) external onlyIssuer {
_updateDebtCacheValidity(currentlyInvalid);
}
function updateCachedsUSDDebt(int amount) external onlyIssuer {
uint delta = SafeDecimalMath.abs(amount);
if (amount > 0) {
_cachedSynthDebt[sUSD] = _cachedSynthDebt[sUSD].add(delta);
_cachedDebt = _cachedDebt.add(delta);
} else {
_cachedSynthDebt[sUSD] = _cachedSynthDebt[sUSD].sub(delta);
_cachedDebt = _cachedDebt.sub(delta);
}
emit DebtCacheUpdated(_cachedDebt);
}
/* ========== INTERNAL FUNCTIONS ========== */
function _updateDebtCacheValidity(bool currentlyInvalid) internal {
if (_cacheInvalid != currentlyInvalid) {
_cacheInvalid = currentlyInvalid;
emit DebtCacheValidityChanged(currentlyInvalid);
}
}
// Updated the global debt according to a rate/supply change in a subset of issued synths.
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
// Compute the cached and current debt sum for the subset of synths provided.
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
// Apply the debt update.
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
// apply the delta between the cachedSum and currentSum
// add currentSum before sub cachedSum to prevent overflow as cachedSum > debt for large amount of excluded debt
debt = debt.add(currentSum).sub(cachedSum);
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
// Invalidate the cache if necessary
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
/* ========== EVENTS ========== */
event DebtCacheUpdated(uint cachedDebt);
event DebtCacheSnapshotTaken(uint timestamp);
event DebtCacheValidityChanged(bool indexed isInvalid);
} | ========== VIEWS ========== / | function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
}
}
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](6);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYSTEMSTATUS;
newAddresses[4] = CONTRACT_COLLATERALMANAGER;
newAddresses[5] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
| 7,765,369 |
./full_match/3/0xAEF5084e3Aef177Ee8ac09116c87649261074028/sources/CryptoCatsMarketV2.sol | require(etheria.getOwner(col, row) != msg.sender); | function createAuction(uint catIndex) public {
cryptocats.buyCat(catIndex);
}
| 8,240,736 |
// SPDX-License-Identifier: MIT
/**
* @title BoredMiladys contract
* @dev Extends ERC721A Non-Fungible Token Standard basic implementation
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (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() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (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'
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");
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @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);
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/TwistedToonz.sol
// Creator: Chiru Labs
pragma solidity ^0.8.0;
/**
* @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..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 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;
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");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; 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 == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
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 uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), "ERC721A: number minted query for the zero address");
return uint256(_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 {
for (uint256 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[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 virtual override {
_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 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 = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; 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 = uint64(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 {}
}
contract BoredMiladys is ERC721A, Ownable, ReentrancyGuard {
string public baseURI;
string public BORED_MILADY_PROVENANCE = "";
uint public MAX_BORED_MILADYS = 2069;
uint public price = 0.06 ether;
uint public maxPerTx = 30;
uint public maxPerWallet = 30;
uint public nextOwnerToExplicitlySet;
bool public canMintBoredMiladys;
constructor()
ERC721A("BoredMilady", "BMIL")
{}
function mintBoredMiladys(uint256 quantity) external payable
{
require(canMintBoredMiladys, "no mint yet");
require(msg.sender == tx.origin,"please try again you are not who you say.");
require( totalSupply() + quantity < MAX_BORED_MILADYS + 1,"SOLD OUT TOO BORED");
require(msg.value == quantity * price,"send exact amount pls");
require( quantity < maxPerTx + 1, "too many in transaction!");
require(numberMinted(msg.sender) + quantity <= maxPerWallet,"minting too many on this wallet lol");
_safeMint(msg.sender, quantity);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BORED_MILADY_PROVENANCE = provenanceHash;
}
function reserveBoredMiladys(uint256 quantity) external onlyOwner
{
require(totalSupply() + quantity < MAX_BORED_MILADYS + 1,"not enough to reserve");
_safeMint(msg.sender, quantity);
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string calldata baseURI_) external onlyOwner {
baseURI = baseURI_;
}
function setOwnersExplicit(uint256 quantity) external onlyOwner nonReentrant {
_setOwnersExplicit(quantity);
}
function toggleMinting() external onlyOwner {
canMintBoredMiladys = !canMintBoredMiladys;
}
function withdraw() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
function setPrice(uint256 price_) external onlyOwner {
price = price_;
}
function setMaxPerTx(uint256 maxPerTx_) external onlyOwner {
maxPerTx = maxPerTx_;
}
function setMaxPerWallet(uint256 maxPerWallet_) external onlyOwner {
maxPerWallet = maxPerWallet_;
}
function setMAX_BORED_MILADYS(uint256 MAX_BORED_MILADYS_) external onlyOwner {
MAX_BORED_MILADYS = MAX_BORED_MILADYS_;
}
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
require(quantity != 0, "quantity must be nonzero");
require(currentIndex != 0, "no tokens minted yet");
uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet;
require(_nextOwnerToExplicitlySet < currentIndex, "all ownerships have been set");
// Index underflow is impossible.
// Counter or index overflow is incredibly unrealistic.
unchecked {
uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1;
// Set the end index to be the last token index
if (endIndex + 1 > currentIndex) {
endIndex = currentIndex - 1;
}
for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i].addr = ownership.addr;
_ownerships[i].startTimestamp = ownership.startTimestamp;
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
}
} | 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./ Overflows are incredibly unrealistic. balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2128) - 1 updatedIndex overflows if currentIndex + quantity > 1.56e77 (2256) - 1 | 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);
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; 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);
}
| 251,647 |
./full_match/11155111/0x7c045ecB589D4fF5c06B712C2d6BB1e855f4a719/sources/contracts/NFT.sol | ============================================================ Finance Management ============================================================ | function withdraw() external onlyRole(DEFAULT_ADMIN_ROLE) {
require(os, "Withdraw not successful");
}
| 3,800,199 |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
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;
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File contracts/ERC165.sol
pragma solidity ^0.8.7;
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File contracts/Drrt.sol
pragma solidity ^0.8.7;
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint tokenIndex, bytes calldata data) external returns (bytes4);
}
contract Drrt is Context, ERC165, Ownable, IERC721Metadata {
using SafeMath for uint;
using Strings for uint;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
uint public constant MAX_TOKENS_MINT_AT_ONCE = 10;
uint public constant MAX_TOKENS_SUPPLY = 9090;
uint public constant TOKEN_PRICE = 60000000000000000;
uint public constant TOKEN_REDUCED_PRICE = 50000000000000000;
uint private constant MAX_GIVEAWAY_TOKENS = 110;
string private constant NAME = 'DRRT';
string private constant SYMBOL = 'DRRT';
uint private _saleStart;
string private _baseURI;
uint private _givenTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping (address => EnumerableSet.UintSet) private _holderTokens;
mapping (uint => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
constructor() {
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the balance of the specified address.
* @param tokenOowner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address tokenOowner) external view override returns (uint) {
require(tokenOowner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[tokenOowner].length();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenIndex uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint tokenIndex) public view override returns (address) {
return _tokenOwners.get(tokenIndex, "ERC721: owner query for nonexistent token");
}
/**
* @dev A descriptive name for a collection of NFTs in this contract
*
* @return descriptive name.
*/
function name() external pure override returns (string memory) {
return NAME;
}
/**
* @dev An abbreviated name for NFTs in this contract
*
* @return abbreviated name (symbol).
*/
function symbol() external pure override returns (string memory) {
return SYMBOL;
}
/**
* @dev function to set the base URI of the collection
*
* @param baseURI base URI string.
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_baseURI = baseURI;
}
/**
* @dev Returns the NFT index owned by the user
*
* @param tokenOowner address.
* @param index Index in the list of owned tokens by address.
*
* @return token index in the collection.
*/
function tokenOfOwnerByIndex(address tokenOowner, uint index) external view returns (uint) {
return _holderTokens[tokenOowner].at(index);
}
/**
* @dev Returns the total amount of tokens stored by the contract.
*
* @return total amount of tokens.
*/
function totalSupply() public view returns (uint) {
return _tokenOwners.length();
}
/**
* @dev Starts the sale of NFTs
*/
function startSale() external onlyOwner {
require(_saleStart == 0, "Sale already started");
_saleStart = block.timestamp;
}
/**
* @dev Function checks if the sale already started
*
* @return true if sale started or false if sale not started.
*/
function isSaleStarted() external view returns (bool) {
return _saleStart > 0;
}
/**
* @dev Function mints one giveaway NFT and sends to the address
*
* @param to address of NFT reciever.
*/
function mintGiveaway(address to) external onlyOwner {
require(_givenTokens <= MAX_GIVEAWAY_TOKENS, "Giveaway limit exceeded");
_givenTokens++;
_safeMint(to, totalSupply());
}
/**
* @dev Function mints the amount of NFTs and sends them to the executor's address
*
* @param tokenAmount amount of NFTs for minting.
*/
function mint(uint tokenAmount) external payable {
require(_saleStart != 0, "Sale is not started");
require(tokenAmount > 0, "Tokens amount cannot be 0");
require(totalSupply().add(tokenAmount) - _givenTokens <= MAX_TOKENS_SUPPLY - MAX_GIVEAWAY_TOKENS, "Purchase would exceed max supply");
require(tokenAmount <= MAX_TOKENS_MINT_AT_ONCE, "Can only mint 10 tokens per request");
uint price;
if (block.timestamp < _saleStart + 86400) {
price = TOKEN_REDUCED_PRICE * tokenAmount;
} else {
price = TOKEN_PRICE * tokenAmount;
}
require(msg.value >= price, "Ether value sent is not correct");
for (uint i = 0; i < tokenAmount; i++) {
_safeMint(_msgSender(), totalSupply());
}
if (msg.value - price > 0) {
payable(_msgSender()).transfer(msg.value - price);
}
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
* @param tokenIndex uint256 ID of the token
*/
function tokenURI(uint tokenIndex) external view returns (string memory) {
require(_exists(tokenIndex), "Token does not exist");
return bytes(_baseURI).length != 0 ? string(abi.encodePacked(_baseURI, tokenIndex.toString())) : "";
}
/**
* @dev Transfers all founds to the owner's address
* Can only be called by the owner of the contract.
*/
function withdraw() onlyOwner external {
uint balance = address(this).balance;
if (balance > 0) {
payable(_msgSender()).transfer(balance);
}
}
/**
* @dev Approves another address to transfer the given token ID
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenIndex uint256 ID of the token to be approved
*/
function approve(address to, uint tokenIndex) external virtual override {
address tokenOowner = ownerOf(tokenIndex);
require(to != tokenOowner, "ERC721: approval to current owner");
require(_msgSender() == tokenOowner || isApprovedForAll(tokenOowner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenIndex);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenIndex uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint tokenIndex) public view override returns (address) {
require(_exists(tokenIndex), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenIndex];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param tokenOowner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address tokenOowner, address operator) public view override returns (bool) {
return _operatorApprovals[tokenOowner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenIndex uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint tokenIndex) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenIndex), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenIndex);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenIndex uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint tokenIndex) public virtual override {
safeTransferFrom(from, to, tokenIndex, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenIndex uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint tokenIndex, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenIndex), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenIndex, _data);
}
/**
* @dev Internal function for safe transfer
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenIndex uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransfer(address from, address to, uint tokenIndex, bytes memory _data) internal virtual {
_transfer(from, to, tokenIndex);
require(_checkOnERC721Received(from, to, tokenIndex, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenIndex uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint tokenIndex) internal view returns (bool) {
return _tokenOwners.contains(tokenIndex);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenIndex uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint tokenIndex) internal view returns (bool) {
require(_exists(tokenIndex), "ERC721: operator query for nonexistent token");
address tokenOowner = ownerOf(tokenIndex);
return (spender == tokenOowner || getApproved(tokenIndex) == spender || isApprovedForAll(tokenOowner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenIndex uint256 ID of the token to be minted
*/
function _safeMint(address to, uint tokenIndex) internal virtual {
_safeMint(to, tokenIndex, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenIndex uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint tokenIndex, bytes memory _data) internal virtual {
_mint(to, tokenIndex);
require(_checkOnERC721Received(address(0), to, tokenIndex, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenIndex uint256 ID of the token to be minted
*/
function _mint(address to, uint tokenIndex) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenIndex), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenIndex);
_holderTokens[to].add(tokenIndex);
_tokenOwners.set(tokenIndex, to);
emit Transfer(address(0), to, tokenIndex);
}
/**
* @dev Internal function for transfer
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenIndex uint256 ID of the token to be transferred
*/
function _transfer(address from, address to, uint tokenIndex) internal virtual {
require(ownerOf(tokenIndex) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenIndex);
_approve(address(0), tokenIndex);
_holderTokens[from].remove(tokenIndex);
_holderTokens[to].add(tokenIndex);
_tokenOwners.set(tokenIndex, to);
emit Transfer(from, to, tokenIndex);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenIndex 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, uint tokenIndex, bytes memory _data) private returns (bool) {
if (!to.isContract()) return true;
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenIndex,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Internal function for approve another address to transfer the given token ID
* @param to address to be approved for the given token ID
* @param tokenIndex uint256 ID of the token to be approved
*/
function _approve(address to, uint tokenIndex) private {
_tokenApprovals[tokenIndex] = to;
emit Approval(ownerOf(tokenIndex), to, tokenIndex);
}
/**
* @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, uint tokenIndex) internal virtual {}
} | Returns the URI for a given token ID. May return an empty string. If the token's URI is non-empty and a base URI was set (via {_setBaseURI}), it will be added to the token ID's URI as a prefix. Reverts if the token ID does not exist. tokenIndex uint256 ID of the token/ | function tokenURI(uint tokenIndex) external view returns (string memory) {
require(_exists(tokenIndex), "Token does not exist");
return bytes(_baseURI).length != 0 ? string(abi.encodePacked(_baseURI, tokenIndex.toString())) : "";
}
| 1,335,358 |
// File: contracts/libraries/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function ADD545(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function SUB798(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function MUL266(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/libraries/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
// a library for performing various math operations
library Math {
function MIN959(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function SQRT138(uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event APPROVAL431(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER692(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME749() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL785() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS386() external view returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY975() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF40(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE51(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE455(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER497(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM392(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IHiposwapV1Callee.sol
pragma solidity >=0.5.0;
interface IHiposwapV1Callee {
function HIPOSWAPV1CALL113(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IHiposwapV2Pair.sol
pragma solidity >=0.5.0;
interface IHiposwapV2Pair {
event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP682( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING
event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING
function FACTORY728() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0432() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN165() external view returns (address); //inject NONSTANDARD NAMING
function CURRENTPOOLID0840() external view returns (uint); //inject NONSTANDARD NAMING
function CURRENTPOOLID1169() external view returns (uint); //inject NONSTANDARD NAMING
function GETMAKERPOOL0622(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING
function GETMAKERPOOL1783(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING
function GETRESERVES45() external view returns (uint reserve0, uint reserve1); //inject NONSTANDARD NAMING
function GETBALANCE570() external view returns (uint _balance0, uint _balance1); //inject NONSTANDARD NAMING
function GETMAKER873(address mkAddress) external view returns (uint,address,uint,uint); //inject NONSTANDARD NAMING
function GETFEES121() external view returns (uint _fee0, uint _fee1); //inject NONSTANDARD NAMING
function GETFEEADMINS69() external view returns (uint _feeAdmin0, uint _feeAdmin1); //inject NONSTANDARD NAMING
function GETAVGTIMES842() external view returns (uint _avgTime0, uint _avgTime1); //inject NONSTANDARD NAMING
function TRANSFERFEEADMIN813(address to) external; //inject NONSTANDARD NAMING
function GETFEEPERCENTS417() external view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent); //inject NONSTANDARD NAMING
function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) external; //inject NONSTANDARD NAMING
function GETREMAINPERCENT819() external view returns (uint); //inject NONSTANDARD NAMING
function GETTOTALPERCENT249() external view returns (uint); //inject NONSTANDARD NAMING
function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function ORDER543(address to) external returns (address token, uint amount); //inject NONSTANDARD NAMING
function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external returns (uint, uint); //inject NONSTANDARD NAMING
function GETAMOUNTA17(address to, uint amountB) external view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING
function GETAMOUNTB418(address to, uint amountA) external view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING
function INITIALIZE162(address, address) external; //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract Context {
function _MSGSENDER363() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA700() 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;
}
}
// File: openzeppelin-solidity/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED266(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER363();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED266(address(0), msgSender);
}
function OWNER618() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER77() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER363(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP420() public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED266(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP895(address newOwner) public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED266(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/HiposwapV2Pair.sol
pragma solidity =0.6.6;
contract HiposwapV2Pair is IHiposwapV2Pair, Ownable {
using SafeMath for uint;
bytes4 private constant selector578 = bytes4(keccak256(bytes('transfer(address,uint256)'))); //inject NONSTANDARD NAMING
address public override factory;
address public override token0;
address public override token1;
uint private fee0;
uint private fee1;
uint private feeAdmin0;
uint private feeAdmin1;
uint public totalWeightTime0;
uint public totalWeightTime1;
uint public totalTokens0;
uint public totalTokens1;
uint private avgTime0;
uint private avgTime1;
uint private reserve0;
uint private reserve1;
uint private feeAdminPercent = 5;
uint private feePercent = 10;
uint private totalPercent = 10000;
struct MakerPool {
uint balance; // remain tokenA
uint swapOut; // swapped tokenA
uint swapIn; // received tokenB
uint createTime;
}
MakerPool[] public makerPools0;
MakerPool[] public makerPools1;
uint public override currentPoolId0;
uint public override currentPoolId1;
struct Maker {
uint poolId;
address token;
uint amount;
uint time;
}
mapping(address => Maker) private makers;
uint public constant minimum_switch_pool_time31 = 30 minutes; //inject NONSTANDARD NAMING
uint private unlocked = 1;
modifier LOCK227() { //inject NONSTANDARD NAMING
require(unlocked == 1, 'HiposwapV2Pair: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function GETRESERVES45() public override view returns (uint _reserve0, uint _reserve1) { //inject NONSTANDARD NAMING
_reserve0 = reserve0;
_reserve1 = reserve1;
}
function GETFEES121() public override view returns (uint _fee0, uint _fee1) { //inject NONSTANDARD NAMING
_fee0 = fee0;
_fee1 = fee1;
}
function GETFEEADMINS69() public override view returns (uint _feeAdmin0, uint _feeAdmin1) { //inject NONSTANDARD NAMING
_feeAdmin0 = feeAdmin0;
_feeAdmin1 = feeAdmin1;
}
function GETAVGTIMES842() public override view returns (uint _avgTime0, uint _avgTime1) { //inject NONSTANDARD NAMING
_avgTime0 = avgTime0;
_avgTime1 = avgTime1;
}
function GETFEEPERCENTS417() public override view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent) { //inject NONSTANDARD NAMING
_feeAdminPercent = feeAdminPercent;
_feePercent = feePercent;
_totalPercent = totalPercent;
}
function GETREMAINPERCENT819() public override view returns (uint) { //inject NONSTANDARD NAMING
return totalPercent.SUB798(feeAdminPercent).SUB798(feePercent);
}
function GETTOTALPERCENT249() external override view returns (uint) { //inject NONSTANDARD NAMING
return totalPercent;
}
function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) public override ONLYOWNER77 { //inject NONSTANDARD NAMING
require(_feeAdminPercent.ADD545(_feePercent) < _totalPercent, "HiposwapV2Pair: INVALID_PARAM");
feeAdminPercent = _feeAdminPercent;
feePercent = _feePercent;
totalPercent = _totalPercent;
}
function GETBALANCE570() public override view returns (uint _balance0, uint _balance1) { //inject NONSTANDARD NAMING
_balance0 = IERC20(token0).BALANCEOF40(address(this));
_balance1 = IERC20(token1).BALANCEOF40(address(this));
}
function GETMAKER873(address mkAddress) public override view returns (uint,address,uint,uint) { //inject NONSTANDARD NAMING
Maker memory m = makers[mkAddress];
return (m.poolId, m.token, m.amount, m.time);
}
function GETMAKERPOOL0622(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING
return _GETMAKERPOOL751(true, poolId);
}
function GETMAKERPOOL1783(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING
return _GETMAKERPOOL751(false, poolId);
}
function _GETMAKERPOOL751(bool left, uint poolId) private view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING
MakerPool[] memory mps = left ? makerPools0 : makerPools1;
if (mps.length > poolId) {
MakerPool memory mp = mps[poolId];
return (mp.balance, mp.swapOut, mp.swapIn);
}
}
function _SAFETRANSFER677(address token, address to, uint value) private { //inject NONSTANDARD NAMING
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(selector578, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'HiposwapV2Pair: TRANSFER_FAILED');
}
event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP682( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING
event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function INITIALIZE162(address _token0, address _token1) external override { //inject NONSTANDARD NAMING
require(msg.sender == factory, 'HiposwapV2Pair: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function CHECKMAKERPOOL614(bool left) private { //inject NONSTANDARD NAMING
MakerPool[] storage mps = left ? makerPools0 : makerPools1;
uint currentPoolId = left ? currentPoolId0 : currentPoolId1;
if (mps.length > 0) {
MakerPool storage mp = mps[currentPoolId];
if (mp.swapOut > mp.balance.MUL266(9) && now > mp.createTime.ADD545(minimum_switch_pool_time31)) {
mps.push(MakerPool(0, 0, 0, now));
if (left) {
currentPoolId0 = currentPoolId0.ADD545(1);
mp.swapIn = mp.swapIn.ADD545(fee1);
fee1 = 0;
totalWeightTime0 = 0;
totalTokens0 = 0;
avgTime0 = 0;
} else {
currentPoolId1 = currentPoolId1.ADD545(1);
mp.swapIn = mp.swapIn.ADD545(fee0);
fee0 = 0;
totalWeightTime1 = 0;
totalTokens1 = 0;
avgTime1 = 0;
}
}
} else {
mps.push(MakerPool(0, 0, 0, now));
}
}
function ADDFEE570(bool left, uint fee, uint feeAdmin) private { //inject NONSTANDARD NAMING
if (left) {
fee1 = fee1.ADD545(fee);
feeAdmin1 = feeAdmin1.ADD545(feeAdmin);
} else {
fee0 = fee0.ADD545(fee);
feeAdmin0 = feeAdmin0.ADD545(feeAdmin);
}
}
function CHECKAVGTIME583(bool left, uint time) private view returns (bool isChargeFee) { //inject NONSTANDARD NAMING
if (left) {
if(avgTime0 > 0){
isChargeFee = now < time.ADD545(avgTime0);
}
} else {
if(avgTime1 > 0){
isChargeFee = now < time.ADD545(avgTime1);
}
}
}
function UPDATEAVGTIME392(bool left, uint time, uint amount) private { //inject NONSTANDARD NAMING
if(amount > 0 && now > time) {
uint weight = (now - time).MUL266(amount);
if (left) {
uint _totalWeightTime0 = totalWeightTime0 + weight;
if (_totalWeightTime0 >= totalWeightTime0) {
totalWeightTime0 = _totalWeightTime0;
totalTokens0 = totalTokens0.ADD545(amount);
avgTime0 = totalWeightTime0 / totalTokens0;
} else { // reset if overflow
totalWeightTime0 = 0;
totalTokens0 = 0;
}
} else {
uint _totalWeightTime1 = totalWeightTime1 + weight;
if (_totalWeightTime1 >= totalWeightTime1) {
totalWeightTime1 = _totalWeightTime1;
totalTokens1 = totalTokens1.ADD545(amount);
avgTime1 = totalWeightTime1 / totalTokens1;
} else { // reset if overflow
totalWeightTime1 = 0;
totalTokens1 = 0;
}
}
}
}
function TRANSFERFEEADMIN813(address to) external override ONLYOWNER77{ //inject NONSTANDARD NAMING
require(feeAdmin0 > 0 || feeAdmin1 > 0, "HiposwapV2Pair: EMPTY_ADMIN_FEES");
if (feeAdmin0 > 0) {
_SAFETRANSFER677(token0, to, feeAdmin0);
feeAdmin0 = 0;
}
if (feeAdmin1 > 0) {
_SAFETRANSFER677(token1, to, feeAdmin1);
feeAdmin1 = 0;
}
}
function ORDER543(address to) external override LOCK227 returns (address token, uint amount){ //inject NONSTANDARD NAMING
uint amount0 = IERC20(token0).BALANCEOF40(address(this)).SUB798(reserve0);
uint amount1 = IERC20(token1).BALANCEOF40(address(this)).SUB798(reserve1);
require((amount0 > 0 && amount1 == 0) || (amount0 == 0 && amount1 > 0), "HiposwapV2Pair: INVALID_AMOUNT");
bool left = amount0 > 0;
CHECKMAKERPOOL614(left);
Maker memory mk = makers[to];
if(mk.amount > 0) {
require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN");
bool _left = mk.token == token0;
uint _currentPoolId = _left ? currentPoolId0 : currentPoolId1;
require(_currentPoolId >= mk.poolId, "HiposwapV2Pair: INVALID_POOL_ID");
if(_currentPoolId > mk.poolId){
DEAL573(to);
mk.amount = 0;
}else{
require(left == _left, "HiposwapV2Pair: ONLY_ONE_MAKER_ALLOWED");
}
}
uint currentPoolId = left ? currentPoolId0 : currentPoolId1;
amount = left ? amount0 : amount1;
token = left ? token0 : token1;
makers[to] = Maker(currentPoolId, token, mk.amount.ADD545(amount), now);
emit _MAKER665(to, token, amount, now);
MakerPool storage mp = left ? makerPools0[currentPoolId] : makerPools1[currentPoolId];
mp.balance = mp.balance.ADD545(amount);
(reserve0, reserve1) = GETBALANCE570();
}
function DEAL573(address to) public { //inject NONSTANDARD NAMING
Maker storage mk = makers[to];
require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN");
bool left = mk.token == token0;
MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId];
(uint amountA, uint amountB) = (mk.amount, 0);
if(mp.swapIn > 0 && mp.swapOut > 0){
amountB = Math.MIN959(mk.amount.MUL266(mp.swapIn) / mp.swapOut, mp.swapIn);
uint swapOut = amountB.MUL266(mp.swapOut) / mp.swapIn;
amountA = amountA.SUB798(swapOut);
mp.swapIn = mp.swapIn.SUB798(amountB);
mp.swapOut = mp.swapOut.SUB798(swapOut);
}
if (amountA > mp.balance) {
// if swapOut, swapIn, balance = 3, 2, 0; mk.amount = 1; then amountB = 0, amountA = 1;
uint dust = amountA.SUB798(mp.balance);
ADDFEE570(!left, dust, 0);
mp.swapOut = mp.swapOut.SUB798(dust);
amountA = mp.balance;
}
mp.balance = mp.balance.SUB798(amountA);
(uint amount0, uint amount1) = left ? (amountA, amountB) : (amountB, amountA);
if(amount0 > 0){
_SAFETRANSFER677(token0, to, amount0);
reserve0 = IERC20(token0).BALANCEOF40(address(this));
}
if(amount1 > 0){
_SAFETRANSFER677(token1, to, amount1);
reserve1 = IERC20(token1).BALANCEOF40(address(this));
}
delete makers[to];
}
function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external override LOCK227 ONLYOWNER77 returns (uint, uint){ //inject NONSTANDARD NAMING
require(amount0 > 0 || amount1 > 0, "HiposwapV2Pair: INVALID_AMOUNT");
Maker storage mk = makers[sender];
require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN");
bool left = mk.token == token0;
MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId];
(uint amountA, uint amountB) = left ? (amount0, amount1) : (amount1, amount0);
bool isChargeFee = mk.poolId == (left ? currentPoolId0 : currentPoolId1) && CHECKAVGTIME583(left, mk.time);
uint amountOrigin = mk.amount;
if (amountA > 0) {
uint amountAMax = Math.MIN959(mk.amount, mp.balance);
uint remain = GETREMAINPERCENT819();
amountAMax = isChargeFee ? amountAMax.MUL266(remain) / totalPercent : amountAMax; // 9985/10000
require(amountA <= amountAMax, "HiposwapV2Pair: INSUFFICIENT_AMOUNT");
if(isChargeFee){
uint fee = amountA.MUL266(feePercent) / remain; // 10/9985
uint feeAdmin = amountA.MUL266(feeAdminPercent) / remain; // = 5/9985
amountA = amountA.ADD545(fee).ADD545(feeAdmin);
ADDFEE570(!left, fee, feeAdmin);
}
mk.amount = mk.amount.SUB798(amountA);
mp.balance = mp.balance.SUB798(amountA);
}
if (amountB > 0) {
require(mp.swapIn > 0 && mp.swapOut > 0, "HiposwapV2Pair: INSUFFICIENT_SWAP_BALANCE");
uint amountBMax = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut);
amountBMax = isChargeFee ? amountBMax.MUL266(GETREMAINPERCENT819()) / totalPercent : amountBMax; // 9985/10000
require(amountB <= amountBMax, "HiposwapV2Pair: INSUFFICIENT_SWAP_AMOUNT");
if(isChargeFee){
uint fee = amountB.MUL266(feePercent) / GETREMAINPERCENT819(); // 10/9985
uint feeAdmin = amountB.MUL266(feeAdminPercent) / GETREMAINPERCENT819(); // = 5/9985
amountB = amountB.ADD545(fee).ADD545(feeAdmin);
ADDFEE570(left, fee, feeAdmin);
}else if (mk.poolId == (left ? currentPoolId0 : currentPoolId1)) {
uint rewards = amountB.MUL266(feePercent) / totalPercent; // 10/10000
if(left){
if (rewards > fee1) {
rewards = fee1;
}
{
uint _amount1 = amount1;
amount1 = _amount1.ADD545(rewards);
fee1 = fee1.SUB798(rewards);
}
}else{
if (rewards > fee0) {
rewards = fee0;
}
{// avoid stack too deep
uint _amount0 = amount0;
amount0 = _amount0.ADD545(rewards);
fee0 = fee0.SUB798(rewards);
}
}
}
uint _amountA = amountB.MUL266(mp.swapOut) / mp.swapIn;
mp.swapIn = mp.swapIn.SUB798(amountB);
mk.amount = mk.amount.SUB798(_amountA);
mp.swapOut = mp.swapOut.SUB798(_amountA);
}
UPDATEAVGTIME392(left, mk.time, amountOrigin.SUB798(mk.amount));
if (mk.amount == 0) {
delete makers[sender];
}
if(amount0 > 0){
_SAFETRANSFER677(token0, to, amount0);
reserve0 = IERC20(token0).BALANCEOF40(address(this));
}
if(amount1 > 0){
_SAFETRANSFER677(token1, to, amount1);
reserve1 = IERC20(token1).BALANCEOF40(address(this));
}
return (amount0, amount1);
}
function GETMAKERANDPOOL128(address to) private view returns (Maker memory mk, MakerPool memory mp){ //inject NONSTANDARD NAMING
mk = makers[to];
require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN");
bool left = mk.token == token0;
uint poolId = mk.poolId;
uint currentPoolId = left ? currentPoolId0 : currentPoolId1;
require(poolId >= 0 && poolId <= currentPoolId, "HiposwapV2Pair: INVALID_POOL_ID");
mp = left ? makerPools0[poolId] : makerPools1[poolId];
}
// amountB is exact
function GETAMOUNTA17(address to, uint amountB) external override view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING
(Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to);
bool left = mk.token == token0;
uint currentPoolId = left ? currentPoolId0 : currentPoolId1;
bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time);
uint remain = GETREMAINPERCENT819();
if(amountB > 0){
if(mp.swapIn > 0 && mp.swapOut > 0){
uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount; // 9985/10000
uint swapIn = isChargeFee ? mp.swapIn.MUL266(remain) / totalPercent : mp.swapIn;
uint amountBMax = Math.MIN959(amountB, Math.MIN959(swapIn, mkAmount.MUL266(mp.swapIn) / mp.swapOut));
uint amountAMax = amountBMax.MUL266(mp.swapOut) / mp.swapIn;
amountAMax = isChargeFee ? amountAMax.MUL266(totalPercent) / remain : amountAMax;
mk.amount = mk.amount.SUB798(amountAMax);
_amountB = amountBMax;
if (!isChargeFee && mk.poolId == currentPoolId) {
uint tmp = _amountB; // avoid stack too deep
uint rewards = tmp.MUL266(feePercent) / totalPercent;
if(left){
if (rewards > fee1) {
rewards = fee1;
}
}else{
if (rewards > fee0) {
rewards = fee0;
}
}
rewardsB = rewards;
}
}
}
amountA = Math.MIN959(mk.amount, mp.balance);
remainA = mk.amount.SUB798(amountA);
amountA = isChargeFee ? amountA.MUL266(remain) / totalPercent : amountA;
}
// amountA is exact
function GETAMOUNTB418(address to, uint amountA) external override view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING
(Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to);
bool left = mk.token == token0;
uint currentPoolId = left ? currentPoolId0 : currentPoolId1;
bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time);
uint remain = GETREMAINPERCENT819();
if(amountA > 0){
uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount;
uint mpBalance = isChargeFee ? mp.balance.MUL266(remain) / totalPercent : mp.balance;
_amountA = Math.MIN959(Math.MIN959(amountA, mkAmount), mpBalance);
if (_amountA == mkAmount) {
mk.amount = 0;
} else {
mk.amount = mk.amount.SUB798(isChargeFee ? _amountA.MUL266(totalPercent) / remain : _amountA);
}
}
if(mp.swapIn > 0 && mp.swapOut > 0){
amountB = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut);
mk.amount = mk.amount.SUB798(amountB.MUL266(mp.swapOut) / mp.swapIn);
if (isChargeFee) {
amountB = amountB.MUL266(remain) / totalPercent;
} else if (mk.poolId == currentPoolId) {
uint rewards = amountB.MUL266(feePercent) / totalPercent;
if(left){
if (rewards > fee1) {
rewards = fee1;
}
}else{
if (rewards > fee0) {
rewards = fee0;
}
}
rewardsB = rewards;
}
}
remainA = mk.amount;
}
function _UPDATE379(uint balance0, uint balance1) private { //inject NONSTANDARD NAMING
require(balance0 <= uint(-1) && balance1 <= uint(-1), 'HiposwapV2Pair: OVERFLOW');
reserve0 = balance0;
reserve1 = balance1;
emit SYNC847(reserve0, reserve1);
}
function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override LOCK227 { //inject NONSTANDARD NAMING
require(amount0Out > 0 || amount1Out > 0, 'HiposwapV2Pair: INSUFFICIENT_OUTPUT_AMOUNT');
(uint _reserve0, uint _reserve1) = GETRESERVES45(); // gas savings
require(amount0Out <= _reserve0 && amount1Out <= _reserve1, 'HiposwapV2Pair: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'HiposwapV2Pair: INVALID_TO');
if (amount0Out > 0) _SAFETRANSFER677(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _SAFETRANSFER677(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IHiposwapV1Callee(to).HIPOSWAPV1CALL113(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).BALANCEOF40(address(this));
balance1 = IERC20(_token1).BALANCEOF40(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'HiposwapV2Pair: INSUFFICIENT_INPUT_AMOUNT');
if (amount0In > 0) {
uint fee = amount0In.MUL266(feePercent) / totalPercent; // = 10/10000
uint feeAdmin = amount0In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000
uint swapIn = amount0In.SUB798(fee).SUB798(feeAdmin);
MakerPool storage mp = makerPools1[currentPoolId1];
mp.swapIn = mp.swapIn.ADD545(swapIn);
mp.swapOut = mp.swapOut.ADD545(amount1Out);
mp.balance = mp.balance.SUB798(amount1Out);
ADDFEE570(false, fee, feeAdmin);
}
if (amount1In >0) {
uint fee = amount1In.MUL266(feePercent) / totalPercent; // = 10/10000
uint feeAdmin = amount1In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000
uint swapIn = amount1In.SUB798(fee).SUB798(feeAdmin);
MakerPool storage mp = makerPools0[currentPoolId0];
mp.swapIn = mp.swapIn.ADD545(swapIn);
mp.swapOut = mp.swapOut.ADD545(amount0Out);
mp.balance = mp.balance.SUB798(amount0Out);
ADDFEE570(true, fee, feeAdmin);
}
_UPDATE379(balance0, balance1);
emit SWAP682(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
}
// File: contracts/interfaces/IHiposwapV2Util.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
interface IHiposwapV2Util {
function PAIRCREATIONCODE232() external returns (bytes memory bytecode); //inject NONSTANDARD NAMING
}
// File: contracts/HiposwapV2Util.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.6.6;
contract HiposwapV2Util is IHiposwapV2Util {
function PAIRCREATIONCODE232() external override returns (bytes memory bytecode){ //inject NONSTANDARD NAMING
bytecode = type(HiposwapV2Pair).creationCode;
}
} | inject NONSTANDARD NAMING | function GETREMAINPERCENT819() public override view returns (uint) { | 7,324,470 |
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// 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);
}
// Dependency 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;
}
}
// Dependency file: @openzeppelin/contracts/utils/Address.sol
// pragma solidity ^0.6.2;
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/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");
}
}
}
// Dependency 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;
}
}
// Dependency file: contracts/common/Initializable.sol
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// pragma solidity 0.6.10;
/**
* @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;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// Dependency file: contracts/common/UpgradeableClaimable.sol
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {Initializable} from "contracts/common/Initializable.sol";
/**
* @title UpgradeableClaimable
* @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. Since
* this contract combines Claimable and UpgradableOwnable contracts, ownership
* can be later change via 2 step method {transferOwnership} and {claimOwnership}
*
* 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 UpgradeableClaimable is Initializable, Context {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting a custom initial owner of choice.
* @param __owner Initial owner of contract to be set.
*/
function initialize(address __owner) internal initializer {
_owner = __owner;
emit OwnershipTransferred(address(0), __owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(_owner, _pendingOwner);
_owner = _pendingOwner;
_pendingOwner = address(0);
}
}
// Dependency file: contracts/truefi2/interface/ITrueStrategy.sol
// pragma solidity 0.6.10;
interface ITrueStrategy {
/**
* @dev put `amount` of tokens into the strategy
* As a result of the deposit value of the strategy should increase by at least 98% of amount
*/
function deposit(uint256 amount) external;
/**
* @dev pull at least `minAmount` of tokens from strategy and transfer to the pool
*/
function withdraw(uint256 minAmount) external;
/**
* @dev withdraw everything from strategy
* As a result of calling withdrawAll(),at least 98% of strategy's value should be transferred to the pool
* Value must become 0
*/
function withdrawAll() external;
/// @dev value evaluated to Pool's tokens
function value() external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/IYToken.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IYToken is IERC20 {
function getPricePerFullShare() external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/ICurve.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {IYToken} from "contracts/truefi/interface/IYToken.sol";
interface ICurve {
function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
interface ICurveGauge {
function balanceOf(address depositor) external view returns (uint256);
function minter() external returns (ICurveMinter);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
interface ICurveMinter {
function mint(address gauge) external;
function token() external view returns (IERC20);
}
interface ICurvePool {
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool donate_dust
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function token() external view returns (IERC20);
function curve() external view returns (ICurve);
function coins(int128 id) external view returns (IYToken);
}
// Dependency file: contracts/truefi/interface/ICrvPriceOracle.sol
// pragma solidity 0.6.10;
interface ICrvPriceOracle {
function usdToCrv(uint256 amount) external view returns (uint256);
function crvToUsd(uint256 amount) external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/IUniswapRouter.sol
// pragma solidity 0.6.10;
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Dependency file: contracts/common/UpgradeableERC20.sol
// pragma solidity 0.6.10;
// import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {Initializable} from "contracts/common/Initializable.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 Initializable, 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.
*/
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 virtual view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override 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 virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override 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 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 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 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 {}
function updateNameAndSymbol(string memory __name, string memory __symbol) internal {
_name = __name;
_symbol = __symbol;
}
}
// Dependency file: contracts/truefi2/interface/ILoanToken2.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {ERC20} from "contracts/common/UpgradeableERC20.sol";
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
interface ILoanToken2 is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function pool() external view returns (ITrueFiPool2);
function profit() external view returns (uint256);
function status() external view returns (Status);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function token() external view returns (ERC20);
function version() external pure returns (uint8);
}
//interface IContractWithPool {
// function pool() external view returns (ITrueFiPool2);
//}
//
//// Had to be split because of multiple inheritance problem
//interface ILoanToken2 is ILoanToken, IContractWithPool {
//
//}
// Dependency file: contracts/truefi2/interface/ITrueLender2.sol
// pragma solidity 0.6.10;
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
// import {ILoanToken2} from "contracts/truefi2/interface/ILoanToken2.sol";
interface ITrueLender2 {
// @dev calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
// @dev distribute a basket of tokens for exiting user
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
function transferAllLoanTokens(ILoanToken2 loan, address recipient) external;
}
// Dependency file: contracts/truefi2/interface/IERC20WithDecimals.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20WithDecimals is IERC20 {
function decimals() external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/ITrueFiPoolOracle.sol
// pragma solidity 0.6.10;
// import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol";
/**
* @dev Oracle that converts any token to and from TRU
* Used for liquidations and valuing of liquidated TRU in the pool
*/
interface ITrueFiPoolOracle {
// token address
function token() external view returns (IERC20WithDecimals);
// amount of tokens 1 TRU is worth
function truToToken(uint256 truAmount) external view returns (uint256);
// amount of TRU 1 token is worth
function tokenToTru(uint256 tokenAmount) external view returns (uint256);
// USD price of token with 18 decimals
function tokenToUsd(uint256 tokenAmount) external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/I1Inch3.sol
// pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface I1Inch3 {
struct SwapDescription {
address srcToken;
address dstToken;
address srcReceiver;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
function swap(
address caller,
SwapDescription calldata desc,
bytes calldata data
)
external
returns (
uint256 returnAmount,
uint256 gasLeft,
uint256 chiSpent
);
function unoswap(
address srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata /* pools */
) external payable returns (uint256 returnAmount);
}
// Dependency file: contracts/truefi2/interface/ISAFU.sol
// pragma solidity 0.6.10;
interface ISAFU {
function poolDeficit(address pool) external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/ITrueFiPool2.sol
// pragma solidity 0.6.10;
// import {ERC20, IERC20} from "contracts/common/UpgradeableERC20.sol";
// import {ITrueLender2, ILoanToken2} from "contracts/truefi2/interface/ITrueLender2.sol";
// import {ITrueFiPoolOracle} from "contracts/truefi2/interface/ITrueFiPoolOracle.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol";
interface ITrueFiPool2 is IERC20 {
function initialize(
ERC20 _token,
ERC20 _stakingToken,
ITrueLender2 _lender,
I1Inch3 __1Inch,
ISAFU safu,
address __owner
) external;
function token() external view returns (ERC20);
function oracle() external view returns (ITrueFiPoolOracle);
/**
* @dev Join the pool by depositing tokens
* @param amount amount of tokens to deposit
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount) external;
/**
* @dev pay borrowed money back to pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 currencyAmount) external;
/**
* @dev SAFU buys LoanTokens from the pool
*/
function liquidate(ILoanToken2 loan) external;
}
// Dependency file: contracts/truefi2/libraries/OneInchExchange.sol
// pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
interface IUniRouter {
function token0() external view returns (address);
function token1() external view returns (address);
}
library OneInchExchange {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
uint256 constant REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000;
event Swapped(I1Inch3.SwapDescription description, uint256 returnedAmount);
/**
* @dev Forward data to 1Inch contract
* @param _1inchExchange address of 1Inch (currently 0x11111112542d85b3ef69ae05771c2dccff4faa26 for mainnet)
* @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap
* [See more](https://docs.1inch.exchange/api/quote-swap#swap)
*
* @return description - description of the swap
*/
function exchange(I1Inch3 _1inchExchange, bytes calldata data)
internal
returns (I1Inch3.SwapDescription memory description, uint256 returnedAmount)
{
if (data[0] == 0x7c) {
// call `swap()`
(, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes));
} else {
// call `unoswap()`
(address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode(
data[4:],
(address, uint256, uint256, bytes32[])
);
description.srcToken = srcToken;
description.amount = amount;
description.minReturnAmount = minReturn;
description.flags = 0;
uint256 lastPath = uint256(pathData[pathData.length - 1]);
IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK));
bool isReverse = lastPath & REVERSE_MASK > 0;
description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1();
description.dstReceiver = address(this);
}
IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount);
uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(_1inchExchange).call(data);
if (!success) {
// Revert with original error message
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
uint256 balanceAfter = IERC20(description.dstToken).balanceOf(description.dstReceiver);
returnedAmount = balanceAfter.sub(balanceBefore);
emit Swapped(description, returnedAmount);
}
}
// Root file: contracts/truefi2/strategies/CurveYearnStrategy.sol
pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {UpgradeableClaimable} from "contracts/common/UpgradeableClaimable.sol";
// import {ITrueStrategy} from "contracts/truefi2/interface/ITrueStrategy.sol";
// import {ICurveGauge, ICurveMinter, ICurvePool, IERC20} from "contracts/truefi/interface/ICurve.sol";
// import {ICrvPriceOracle} from "contracts/truefi/interface/ICrvPriceOracle.sol";
// import {IUniswapRouter} from "contracts/truefi/interface/IUniswapRouter.sol";
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {OneInchExchange} from "contracts/truefi2/libraries/OneInchExchange.sol";
// import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol";
/**
* @dev TrueFi pool strategy that allows depositing stablecoins into Curve Yearn pool (0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51)
* Supports DAI, USDC, USDT and TUSD
* Curve LP tokens are being deposited into Curve Gauge and CRV rewards can be sold on 1Inch exchange and transferred to the pool
*/
contract CurveYearnStrategy is UpgradeableClaimable, ITrueStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IERC20WithDecimals;
using OneInchExchange for I1Inch3;
// Number of tokens in Curve yPool
uint8 public constant N_TOKENS = 4;
// Max slippage during the swap
uint256 public constant MAX_PRICE_SLIPPAGE = 200; // 2%
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
// Index of token in Curve pool
// 0 - DAI
// 1 - USDC
// 2 - USDT
// 3 - TUSD
uint8 public tokenIndex;
ICurvePool public curvePool;
ICurveGauge public curveGauge;
ICurveMinter public minter;
I1Inch3 public _1Inch;
IERC20WithDecimals public token;
address public pool;
// CRV price oracle
ICrvPriceOracle public crvOracle;
// ======= STORAGE DECLARATION END ===========
event OracleChanged(ICrvPriceOracle newOracle);
event Deposited(uint256 depositedAmount, uint256 receivedYAmount);
event Withdrawn(uint256 minAmount, uint256 yAmount);
event WithdrawnAll(uint256 yAmount);
modifier onlyPool() {
require(msg.sender == pool, "CurveYearnStrategy: Can only be called by pool");
_;
}
function initialize(
ITrueFiPool2 _pool,
ICurvePool _curvePool,
ICurveGauge _curveGauge,
ICurveMinter _minter,
I1Inch3 _1inchExchange,
ICrvPriceOracle _crvOracle,
uint8 _tokenIndex
) external initializer {
UpgradeableClaimable.initialize(msg.sender);
token = IERC20WithDecimals(address(_pool.token()));
pool = address(_pool);
curvePool = _curvePool;
curveGauge = _curveGauge;
minter = _minter;
_1Inch = _1inchExchange;
crvOracle = _crvOracle;
tokenIndex = _tokenIndex;
}
/**
* @dev Sets new crv oracle address
* @param _crvOracle new oracle address
*/
function setOracle(ICrvPriceOracle _crvOracle) external onlyOwner {
crvOracle = _crvOracle;
emit OracleChanged(_crvOracle);
}
/**
* @dev Transfer `amount` of `token` from pool and add it as
* liquidity to the Curve yEarn Pool
* Curve LP tokens are deposited into Curve Gauge
* @param amount amount of token to add to curve
*/
function deposit(uint256 amount) external override onlyPool {
token.safeTransferFrom(pool, address(this), amount);
uint256 totalAmount = token.balanceOf(address(this));
uint256[N_TOKENS] memory amounts = [uint256(0), 0, 0, 0];
amounts[tokenIndex] = totalAmount;
token.safeApprove(address(curvePool), totalAmount);
uint256 conservativeMinAmount = calcTokenAmount(totalAmount).mul(999).div(1000);
curvePool.add_liquidity(amounts, conservativeMinAmount);
// stake yCurve tokens in gauge
uint256 yBalance = curvePool.token().balanceOf(address(this));
curvePool.token().safeApprove(address(curveGauge), yBalance);
curveGauge.deposit(yBalance);
emit Deposited(amount, yBalance);
}
/**
* @dev pull at least `minAmount` of tokens from strategy
* Remove token liquidity from curve and transfer to pool
* @param minAmount Minimum amount of tokens to remove from strategy
*/
function withdraw(uint256 minAmount) external override onlyPool {
// get rough estimate of how much yCRV we should sell
uint256 roughCurveTokenAmount = calcTokenAmount(minAmount);
uint256 yBalance = yTokenBalance();
require(roughCurveTokenAmount <= yBalance, "CurveYearnStrategy: Not enough Curve liquidity tokens in pool to cover borrow");
// Try to withdraw a bit more to be safe, but not above the total balance
uint256 conservativeCurveTokenAmount = min(yBalance, roughCurveTokenAmount.mul(1005).div(1000));
// pull tokens from gauge
withdrawFromGaugeIfNecessary(conservativeCurveTokenAmount);
// remove TUSD from curve
curvePool.token().safeApprove(address(curvePool), conservativeCurveTokenAmount);
curvePool.remove_liquidity_one_coin(conservativeCurveTokenAmount, tokenIndex, minAmount, false);
transferAllToPool();
emit Withdrawn(minAmount, conservativeCurveTokenAmount);
}
/**
*@dev withdraw everything from strategy
* Use with caution because Curve slippage is not controlled
*/
function withdrawAll() external override onlyPool {
curveGauge.withdraw(curveGauge.balanceOf(address(this)));
uint256 yBalance = yTokenBalance();
curvePool.token().safeApprove(address(curvePool), yBalance);
curvePool.remove_liquidity_one_coin(yBalance, tokenIndex, 0, false);
transferAllToPool();
emit WithdrawnAll(yBalance);
}
/**
* @dev Total pool value in USD
* @notice Balance of CRV is not included into value of strategy,
* because it cannot be converted to pool tokens automatically
* @return Value of pool in USD
*/
function value() external override view returns (uint256) {
return yTokenValue();
}
/**
* @dev Price of in USD
* @return Oracle price of TRU in USD
*/
function yTokenValue() public view returns (uint256) {
return normalizeDecimals(yTokenBalance().mul(curvePool.curve().get_virtual_price()).div(1 ether));
}
/**
* @dev Get total balance of curve.fi pool tokens
* @return Balance of y pool tokens in this contract
*/
function yTokenBalance() public view returns (uint256) {
return curvePool.token().balanceOf(address(this)).add(curveGauge.balanceOf(address(this)));
}
/**
* @dev Price of CRV in USD
* @return Oracle price of TRU in USD
*/
function crvValue() public view returns (uint256) {
uint256 balance = crvBalance();
if (balance == 0 || address(crvOracle) == address(0)) {
return 0;
}
return normalizeDecimals(conservativePriceEstimation(crvOracle.crvToUsd(balance)));
}
/**
* @dev Get total balance of CRV tokens
* @return Balance of stake tokens in this contract
*/
function crvBalance() public view returns (uint256) {
return minter.token().balanceOf(address(this));
}
/**
* @dev Collect CRV tokens minted by staking at gauge
*/
function collectCrv() external {
minter.mint(address(curveGauge));
}
/**
* @dev Swap collected CRV on 1inch and transfer gains to the pool
* Receiver of the tokens should be the pool
* Revert if resulting exchange price is much smaller than the oracle price
* @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap
* [See more](https://docs.1inch.exchange/api/quote-swap#swap)
*/
function sellCrv(bytes calldata data) external {
(I1Inch3.SwapDescription memory swap, uint256 balanceDiff) = _1Inch.exchange(data);
uint256 expectedGain = normalizeDecimals(crvOracle.crvToUsd(swap.amount));
require(swap.srcToken == address(minter.token()), "CurveYearnStrategy: Source token is not CRV");
require(swap.dstToken == address(token), "CurveYearnStrategy: Destination token is not TUSD");
require(swap.dstReceiver == pool, "CurveYearnStrategy: Receiver is not pool");
require(balanceDiff >= conservativePriceEstimation(expectedGain), "CurveYearnStrategy: Not optimal exchange");
}
/**
* @dev Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens.
* @param currencyAmount amount to calculate for
* @return expected amount minted given currency amount
*/
function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) {
uint256 yTokenAmount = currencyAmount.mul(1e18).div(curvePool.coins(tokenIndex).getPricePerFullShare());
uint256[N_TOKENS] memory yAmounts = [uint256(0), 0, 0, 0];
yAmounts[tokenIndex] = yTokenAmount;
return curvePool.curve().calc_token_amount(yAmounts, true);
}
/**
* @dev ensure enough curve.fi pool tokens are available
* Check if current available amount of TUSD is enough and
* withdraw remainder from gauge
* @param neededAmount amount required
*/
function withdrawFromGaugeIfNecessary(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
/**
* @dev Internal function to transfer entire token balance to pool
*/
function transferAllToPool() internal {
token.safeTransfer(pool, token.balanceOf(address(this)));
}
/**
* @dev Calculate price minus max percentage of slippage during exchange
* This will lead to the pool value become a bit undervalued
* compared to the oracle price but will ensure that the value doesn't drop
* when token exchanges are performed.
*/
function conservativePriceEstimation(uint256 price) internal pure returns (uint256) {
return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000);
}
/**
* @dev Helper function to calculate minimum of `a` and `b`
* @param a First variable to check if minimum
* @param b Second variable to check if minimum
* @return Lowest value between a and b
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
/**
* @dev Helper function to convert between token precision
* @param _value Value to normalize decimals for
* @return Normalized value
*/
function normalizeDecimals(uint256 _value) internal view returns (uint256) {
return _value.mul(10**token.decimals()).div(10**18);
}
} | calculate overall value of the pools distribute a basket of tokens for exiting user | interface ITrueLender2 {
function value(ITrueFiPool2 pool) external view returns (uint256);
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
function transferAllLoanTokens(ILoanToken2 loan, address recipient) external;
}
| 1,201,410 |
./partial_match/1/0xA83D81113F57d63AF7EFDC4a12350365c7871266/sources/ShareTokenSale.sol | End current round after validating all requirements/Call db contract to endemit event | function _end(uint round, uint time) internal {
require(_dbContract.end(round, time), "ShareTokenSaleFactory._end: Can not end current round");
emit EndTokenSale(round, time);
}
| 3,643,392 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.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].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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 defaut 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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @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");
_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");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= 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 { }
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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.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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {
IUniswapV3MintCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import {
IUniswapV3SwapCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {GUniPoolStorage} from "./abstract/GUniPoolStorage.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {TickMath} from "./vendor/uniswap/TickMath.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {
FullMath,
LiquidityAmounts
} from "./vendor/uniswap/LiquidityAmounts.sol";
contract GUniPool is
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
GUniPoolStorage
{
using SafeERC20 for IERC20;
using TickMath for int24;
event Minted(
address receiver,
uint256 mintAmount,
uint256 amount0In,
uint256 amount1In,
uint128 liquidityMinted
);
event Burned(
address receiver,
uint256 burnAmount,
uint256 amount0Out,
uint256 amount1Out,
uint128 liquidityBurned
);
event Rebalance(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidityBefore,
uint128 liquidityAfter
);
event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato) GUniPoolStorage(_gelato) {} // solhint-disable-line no-empty-blocks
/// @notice Uniswap V3 callback fn, called back on pool.mint
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata /*_data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Owed > 0) token0.safeTransfer(msg.sender, amount0Owed);
if (amount1Owed > 0) token1.safeTransfer(msg.sender, amount1Owed);
}
/// @notice Uniswap v3 callback fn, called back on pool.swap
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /*data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Delta > 0)
token0.safeTransfer(msg.sender, uint256(amount0Delta));
else if (amount1Delta > 0)
token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
// User functions => Should be called via a Router
/// @notice mint fungible G-UNI tokens, fractional shares of a Uniswap V3 position
/// @dev to compute the amouint of tokens necessary to mint `mintAmount` see getMintAmounts
/// @param mintAmount The number of G-UNI tokens to mint
/// @param receiver The account to receive the minted tokens
/// @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount`
/// @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount`
/// @return liquidityMinted amount of liquidity added to the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines, code-complexity
function mint(uint256 mintAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityMinted
)
{
require(mintAmount > 0, "mint 0");
uint256 totalSupply = totalSupply();
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
if (totalSupply > 0) {
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
amount0 = FullMath.mulDivRoundingUp(
amount0Current,
mintAmount,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
amount1Current,
mintAmount,
totalSupply
);
} else {
// if supply is 0 mintAmount == liquidity to deposit
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
SafeCast.toUint128(mintAmount)
);
}
// transfer amounts owed to contract
if (amount0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), amount0);
}
if (amount1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), amount1);
}
// deposit as much new liquidity as possible
liquidityMinted = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0,
amount1
);
pool.mint(address(this), lowerTick, upperTick, liquidityMinted, "");
_mint(receiver, mintAmount);
emit Minted(receiver, mintAmount, amount0, amount1, liquidityMinted);
}
/// @notice burn G-UNI tokens (fractional shares of a Uniswap V3 position) and receive tokens
/// @param burnAmount The number of G-UNI tokens to burn
/// @param receiver The account to receive the underlying amounts of token0 and token1
/// @return amount0 amount of token0 transferred to receiver for burning `burnAmount`
/// @return amount1 amount of token1 transferred to receiver for burning `burnAmount`
/// @return liquidityBurned amount of liquidity removed from the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines
function burn(uint256 burnAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityBurned
)
{
require(burnAmount > 0, "burn 0");
uint256 totalSupply = totalSupply();
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_burn(msg.sender, burnAmount);
uint256 liquidityBurned_ =
FullMath.mulDiv(burnAmount, liquidity, totalSupply);
liquidityBurned = SafeCast.toUint128(liquidityBurned_);
(uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidityBurned);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
amount0 =
burn0 +
FullMath.mulDiv(
token0.balanceOf(address(this)) -
burn0 -
managerBalance0 -
gelatoBalance0,
burnAmount,
totalSupply
);
amount1 =
burn1 +
FullMath.mulDiv(
token1.balanceOf(address(this)) -
burn1 -
managerBalance1 -
gelatoBalance1,
burnAmount,
totalSupply
);
if (amount0 > 0) {
token0.safeTransfer(receiver, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(receiver, amount1);
}
emit Burned(receiver, burnAmount, amount0, amount1, liquidityBurned);
}
// Manager Functions => Called by Pool Manager
/// @notice Change the range of underlying UniswapV3 position, only manager can call
/// @dev When changing the range the inventory of token0 and token1 may be rebalanced
/// with a swap to deposit as much liquidity as possible into the new position. Swap parameters
/// can be computed by simulating the whole operation: remove all liquidity, deposit as much
/// as possible into new position, then observe how much of token0 or token1 is leftover.
/// Swap a proportion of this leftover to deposit more liquidity into the position, since
/// any leftover will be unused and sit idle until the next rebalance.
/// @param newLowerTick The new lower bound of the position's range
/// @param newUpperTick The new upper bound of the position's range
/// @param swapThresholdPrice slippage parameter on the swap as a max or min sqrtPriceX96
/// @param swapAmountBPS amount of token to swap as proportion of total. Pass 0 to ignore swap.
/// @param zeroForOne Which token to input into the swap (true = token0, false = token1)
function executiveRebalance(
int24 newLowerTick,
int24 newUpperTick,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) external onlyManager {
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
if (liquidity > 0) {
(, , uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
}
lowerTick = newLowerTick;
upperTick = newUpperTick;
uint256 reinvest0 =
token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0;
uint256 reinvest1 =
token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1;
_deposit(
newLowerTick,
newUpperTick,
reinvest0,
reinvest1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
(uint128 newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity > 0, "new position 0");
emit Rebalance(newLowerTick, newUpperTick, liquidity, newLiquidity);
}
// Gelatofied functions => Automatically called by Gelato
/// @notice Reinvest fees earned into underlying position, only gelato executors can call
/// Position bounds CANNOT be altered by gelato, only manager may via executiveRebalance.
/// Frequency of rebalance configured with gelatoRebalanceBPS, alterable by manager.
function rebalance(
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) external gelatofy(feeAmount, paymentToken) {
if (swapAmountBPS > 0) {
_checkSlippage(swapThresholdPrice, zeroForOne);
}
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_rebalance(
liquidity,
swapThresholdPrice,
swapAmountBPS,
zeroForOne,
feeAmount,
paymentToken
);
(uint128 newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity >= liquidity, "liquidity decrease");
emit Rebalance(lowerTick, upperTick, liquidity, newLiquidity);
}
/// @notice withdraw manager fees accrued, only gelato executors can call.
/// Target account to receive fees is managerTreasury, alterable by manager.
/// Frequency of withdrawals configured with gelatoWithdrawBPS, alterable by manager.
function withdrawManagerBalance(uint256 feeAmount, address feeToken)
external
gelatofy(feeAmount, feeToken)
{
(uint256 amount0, uint256 amount1) =
_balancesToWithdraw(
managerBalance0,
managerBalance1,
feeAmount,
feeToken
);
managerBalance0 = 0;
managerBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(managerTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(managerTreasury, amount1);
}
}
/// @notice withdraw gelato fees accrued, only gelato executors can call.
/// Frequency of withdrawals configured with gelatoWithdrawBPS, alterable by manager.
function withdrawGelatoBalance(uint256 feeAmount, address feeToken)
external
gelatofy(feeAmount, feeToken)
{
(uint256 amount0, uint256 amount1) =
_balancesToWithdraw(
gelatoBalance0,
gelatoBalance1,
feeAmount,
feeToken
);
gelatoBalance0 = 0;
gelatoBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(GELATO, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(GELATO, amount1);
}
}
function _balancesToWithdraw(
uint256 balance0,
uint256 balance1,
uint256 feeAmount,
address feeToken
) internal view returns (uint256 amount0, uint256 amount1) {
if (feeToken == address(token0)) {
require(
(balance0 * gelatoWithdrawBPS) / 10000 >= feeAmount,
"high fee"
);
amount0 = balance0 - feeAmount;
amount1 = balance1;
} else if (feeToken == address(token1)) {
require(
(balance1 * gelatoWithdrawBPS) / 10000 >= feeAmount,
"high fee"
);
amount1 = balance1 - feeAmount;
amount0 = balance0;
} else {
revert("wrong token");
}
}
// View functions
/// @notice compute maximum G-UNI tokens that can be minted from `amount0Max` and `amount1Max`
/// @param amount0Max The maximum amount of token0 to forward on mint
/// @param amount0Max The maximum amount of token1 to forward on mint
/// @return amount0 actual amount of token0 to forward when minting `mintAmount`
/// @return amount1 actual amount of token1 to forward when minting `mintAmount`
/// @return mintAmount maximum number of G-UNI tokens to mint
function getMintAmounts(uint256 amount0Max, uint256 amount1Max)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
uint256 totalSupply = totalSupply();
if (totalSupply > 0) {
(amount0, amount1, mintAmount) = _computeMintAmounts(
totalSupply,
amount0Max,
amount1Max
);
} else {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 newLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0Max,
amount1Max
);
mintAmount = uint256(newLiquidity);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
newLiquidity
);
}
}
/// @notice compute total underlying holdings of the G-UNI token supply
/// includes current liquidity invested in uniswap position, current fees earned
/// and any uninvested leftover (but does not include manager or gelato fees accrued)
/// @return amount0Current current total underlying balance of token0
/// @return amount1Current current total underlying balance of token1
function getUnderlyingBalances()
public
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(uint160 sqrtRatioX96, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
function getUnderlyingBalancesAtPrice(uint160 sqrtRatioX96)
external
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
// solhint-disable-next-line function-max-lines
function _getUnderlyingBalances(uint160 sqrtRatioX96, int24 tick)
internal
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(
uint128 liquidity,
uint256 feeGrowthInside0Last,
uint256 feeGrowthInside1Last,
uint128 tokensOwed0,
uint128 tokensOwed1
) = pool.positions(_getPositionID());
// compute current holdings from liquidity
(amount0Current, amount1Current) = LiquidityAmounts
.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
liquidity
);
// compute current fees earned
uint256 fee0 =
_computeFeesEarned(true, feeGrowthInside0Last, tick, liquidity) +
uint256(tokensOwed0);
uint256 fee1 =
_computeFeesEarned(false, feeGrowthInside1Last, tick, liquidity) +
uint256(tokensOwed1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
// add any leftover in contract to current holdings
amount0Current +=
fee0 +
token0.balanceOf(address(this)) -
managerBalance0 -
gelatoBalance0;
amount1Current +=
fee1 +
token1.balanceOf(address(this)) -
managerBalance1 -
gelatoBalance1;
}
// Private functions
// solhint-disable-next-line function-max-lines
function _rebalance(
uint128 liquidity,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) private {
uint256 leftover0 =
token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0;
uint256 leftover1 =
token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1;
(, , uint256 feesEarned0, uint256 feesEarned1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(feesEarned0, feesEarned1);
(feesEarned0, feesEarned1) = _subtractAdminFees(
feesEarned0,
feesEarned1
);
emit FeesEarned(feesEarned0, feesEarned1);
feesEarned0 += leftover0;
feesEarned1 += leftover1;
if (paymentToken == address(token0)) {
require(
(feesEarned0 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
gelatoBalance0 -
feeAmount;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
gelatoBalance1;
} else if (paymentToken == address(token1)) {
require(
(feesEarned1 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
gelatoBalance0;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
gelatoBalance1 -
feeAmount;
} else {
revert("wrong token");
}
_deposit(
lowerTick,
upperTick,
leftover0,
leftover1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
}
// solhint-disable-next-line function-max-lines
function _withdraw(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidity
)
private
returns (
uint256 burn0,
uint256 burn1,
uint256 fee0,
uint256 fee1
)
{
uint256 preBalance0 = token0.balanceOf(address(this));
uint256 preBalance1 = token1.balanceOf(address(this));
(burn0, burn1) = pool.burn(lowerTick_, upperTick_, liquidity);
pool.collect(
address(this),
lowerTick_,
upperTick_,
type(uint128).max,
type(uint128).max
);
fee0 = token0.balanceOf(address(this)) - preBalance0 - burn0;
fee1 = token1.balanceOf(address(this)) - preBalance1 - burn1;
}
// solhint-disable-next-line function-max-lines
function _deposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) private {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
// First, deposit as much as we can
uint128 baseLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
amount0,
amount1
);
if (baseLiquidity > 0) {
(uint256 amountDeposited0, uint256 amountDeposited1) =
pool.mint(
address(this),
lowerTick_,
upperTick_,
baseLiquidity,
""
);
amount0 -= amountDeposited0;
amount1 -= amountDeposited1;
}
int256 swapAmount =
SafeCast.toInt256(
((zeroForOne ? amount0 : amount1) * swapAmountBPS) / 10000
);
if (swapAmount > 0) {
_swapAndDeposit(
lowerTick_,
upperTick_,
amount0,
amount1,
swapAmount,
swapThresholdPrice,
zeroForOne
);
}
}
function _swapAndDeposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
int256 swapAmount,
uint160 swapThresholdPrice,
bool zeroForOne
) private returns (uint256 finalAmount0, uint256 finalAmount1) {
(int256 amount0Delta, int256 amount1Delta) =
pool.swap(
address(this),
zeroForOne,
swapAmount,
swapThresholdPrice,
""
);
finalAmount0 = uint256(SafeCast.toInt256(amount0) - amount0Delta);
finalAmount1 = uint256(SafeCast.toInt256(amount1) - amount1Delta);
// Add liquidity a second time
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 liquidityAfterSwap =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
finalAmount0,
finalAmount1
);
if (liquidityAfterSwap > 0) {
pool.mint(
address(this),
lowerTick_,
upperTick_,
liquidityAfterSwap,
""
);
}
}
// solhint-disable-next-line function-max-lines, code-complexity
function _computeMintAmounts(
uint256 totalSupply,
uint256 amount0Max,
uint256 amount1Max
)
private
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
// compute proportional amount of tokens to mint
if (amount0Current == 0 && amount1Current > 0) {
mintAmount = FullMath.mulDiv(
amount1Max,
totalSupply,
amount1Current
);
} else if (amount1Current == 0 && amount0Current > 0) {
mintAmount = FullMath.mulDiv(
amount0Max,
totalSupply,
amount0Current
);
} else if (amount0Current == 0 && amount1Current == 0) {
revert("");
} else {
// only if both are non-zero
uint256 amount0Mint =
FullMath.mulDiv(amount0Max, totalSupply, amount0Current);
uint256 amount1Mint =
FullMath.mulDiv(amount1Max, totalSupply, amount1Current);
require(amount0Mint > 0 && amount1Mint > 0, "mint 0");
mintAmount = amount0Mint < amount1Mint ? amount0Mint : amount1Mint;
}
// compute amounts owed to contract
amount0 = FullMath.mulDivRoundingUp(
mintAmount,
amount0Current,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
mintAmount,
amount1Current,
totalSupply
);
}
// solhint-disable-next-line function-max-lines
function _computeFeesEarned(
bool isZero,
uint256 feeGrowthInsideLast,
int24 tick,
uint128 liquidity
) private view returns (uint256 fee) {
uint256 feeGrowthOutsideLower;
uint256 feeGrowthOutsideUpper;
uint256 feeGrowthGlobal;
if (isZero) {
feeGrowthGlobal = pool.feeGrowthGlobal0X128();
(, , feeGrowthOutsideLower, , , , , ) = pool.ticks(lowerTick);
(, , feeGrowthOutsideUpper, , , , , ) = pool.ticks(upperTick);
} else {
feeGrowthGlobal = pool.feeGrowthGlobal1X128();
(, , , feeGrowthOutsideLower, , , , ) = pool.ticks(lowerTick);
(, , , feeGrowthOutsideUpper, , , , ) = pool.ticks(upperTick);
}
unchecked {
// calculate fee growth below
uint256 feeGrowthBelow;
if (tick >= lowerTick) {
feeGrowthBelow = feeGrowthOutsideLower;
} else {
feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
}
// calculate fee growth above
uint256 feeGrowthAbove;
if (tick < upperTick) {
feeGrowthAbove = feeGrowthOutsideUpper;
} else {
feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
}
uint256 feeGrowthInside =
feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;
fee = FullMath.mulDiv(
liquidity,
feeGrowthInside - feeGrowthInsideLast,
0x100000000000000000000000000000000
);
}
}
function _applyFees(uint256 _fee0, uint256 _fee1) private {
gelatoBalance0 += (_fee0 * gelatoFeeBPS) / 10000;
gelatoBalance1 += (_fee1 * gelatoFeeBPS) / 10000;
managerBalance0 += (_fee0 * managerFeeBPS) / 10000;
managerBalance1 += (_fee1 * managerFeeBPS) / 10000;
}
function _subtractAdminFees(uint256 rawFee0, uint256 rawFee1)
private
view
returns (uint256 fee0, uint256 fee1)
{
uint256 deduct0 = (rawFee0 * (gelatoFeeBPS + managerFeeBPS)) / 10000;
uint256 deduct1 = (rawFee1 * (gelatoFeeBPS + managerFeeBPS)) / 10000;
fee0 = rawFee0 - deduct0;
fee1 = rawFee1 - deduct1;
}
function _checkSlippage(uint160 swapThresholdPrice, bool zeroForOne)
private
view
{
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = gelatoSlippageInterval;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
require(tickCumulatives.length == 2, "array len");
uint160 avgSqrtRatioX96;
unchecked {
int24 avgTick =
int24(
(tickCumulatives[1] - tickCumulatives[0]) /
int56(uint56(gelatoSlippageInterval))
);
avgSqrtRatioX96 = avgTick.getSqrtRatioAtTick();
}
uint160 maxSlippage = (avgSqrtRatioX96 * gelatoSlippageBPS) / 10000;
if (zeroForOne) {
require(
swapThresholdPrice >= avgSqrtRatioX96 - maxSlippage,
"high slippage"
);
} else {
require(
swapThresholdPrice <= avgSqrtRatioX96 + maxSlippage,
"high slippage"
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Gelatofied} from "./Gelatofied.sol";
import {OwnableUninitialized} from "./OwnableUninitialized.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
/// @dev Single Global upgradeable state var storage base: APPEND ONLY
/// @dev Add all inherited contracts with state vars here: APPEND ONLY
/// @dev ERC20Upgradable Includes Initialize
// solhint-disable-next-line max-states-count
abstract contract GUniPoolStorage is
ERC20Upgradeable, /* XXXX DONT MODIFY ORDERING XXXX */
ReentrancyGuardUpgradeable,
OwnableUninitialized,
Gelatofied
// APPEND ADDITIONAL BASE WITH STATE VARS BELOW:
// XXXX DONT MODIFY ORDERING XXXX
{
// solhint-disable-next-line const-name-snakecase
string public constant version = "1.0.0";
// solhint-disable-next-line const-name-snakecase
uint16 public constant gelatoFeeBPS = 100;
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
int24 public lowerTick;
int24 public upperTick;
uint16 public gelatoRebalanceBPS;
uint16 public gelatoWithdrawBPS;
uint16 public gelatoSlippageBPS;
uint32 public gelatoSlippageInterval;
uint16 public managerFeeBPS;
address public managerTreasury;
uint256 public managerBalance0;
uint256 public managerBalance1;
uint256 public gelatoBalance0;
uint256 public gelatoBalance1;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
// APPPEND ADDITIONAL STATE VARS BELOW:
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
event UpdateAdminTreasury(
address oldAdminTreasury,
address newAdminTreasury
);
event UpdateGelatoParams(
uint16 gelatoRebalanceBPS,
uint16 gelatoWithdrawBPS,
uint16 gelatoSlippageBPS,
uint32 gelatoSlippageInterval
);
event SetManagerFee(uint16 managerFee);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato) Gelatofied(_gelato) {} // solhint-disable-line no-empty-blocks
/// @notice initialize storage variables on a new G-UNI pool, only called once
/// @param _name name of G-UNI token
/// @param _symbol symbol of G-UNI token
/// @param _pool address of Uniswap V3 pool
/// @param _managerFeeBPS proportion of fees earned that go to manager treasury
/// note that the 4 above params are NOT UPDATEABLE AFTER INILIALIZATION
/// @param _lowerTick initial lowerTick (only changeable with executiveRebalance)
/// @param _lowerTick initial upperTick (only changeable with executiveRebalance)
/// @param _manager_ address of manager (ownership can be transferred)
function initialize(
string memory _name,
string memory _symbol,
address _pool,
uint16 _managerFeeBPS,
int24 _lowerTick,
int24 _upperTick,
address _manager_
) external initializer {
require(_managerFeeBPS <= 10000 - gelatoFeeBPS, "mBPS");
// these variables are immutable after initialization
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
managerFeeBPS = _managerFeeBPS; // if set to 0 here manager can still initialize later
// these variables can be udpated by the manager
gelatoSlippageInterval = 5 minutes; // default: last five minutes;
gelatoSlippageBPS = 500; // default: 5% slippage
gelatoWithdrawBPS = 100; // default: only auto withdraw if tx fee is lt 1% withdrawn
gelatoRebalanceBPS = 200; // default: only rebalance if tx fee is lt 2% reinvested
managerTreasury = _manager_; // default: treasury is admin
lowerTick = _lowerTick;
upperTick = _upperTick;
_manager = _manager_;
// e.g. "Gelato Uniswap V3 USDC/DAI LP" and "G-UNI"
__ERC20_init(_name, _symbol);
__ReentrancyGuard_init();
}
/// @notice change configurable parameters, only manager can call
/// @param newRebalanceBPS controls frequency of gelato rebalances: gas fee to execute
/// rebalance can be gelatoRebalanceBPS proportion of fees earned since last rebalance
/// @param newWithdrawBPS controls frequency of gelato withdrawals: gas fee to execute
/// withdrawal can be gelatoWithdrawBPS proportion of fees accrued since last withdraw
/// @param newSlippageBPS maximum slippage on swaps during gelato rebalance
/// @param newSlippageInterval length of time for TWAP used in computing slippage on swaps
/// @param newTreasury address where managerFee withdrawals are sent
// solhint-disable-next-line code-complexity
function updateGelatoParams(
uint16 newRebalanceBPS,
uint16 newWithdrawBPS,
uint16 newSlippageBPS,
uint32 newSlippageInterval,
address newTreasury
) external onlyManager {
require(newWithdrawBPS <= 10000, "BPS");
require(newRebalanceBPS <= 10000, "BPS");
require(newSlippageBPS <= 10000, "BPS");
emit UpdateGelatoParams(
newRebalanceBPS,
newWithdrawBPS,
newSlippageBPS,
newSlippageInterval
);
if (newRebalanceBPS != 0) gelatoRebalanceBPS = newRebalanceBPS;
if (newWithdrawBPS != 0) gelatoWithdrawBPS = newWithdrawBPS;
if (newSlippageBPS != 0) gelatoSlippageBPS = newSlippageBPS;
if (newSlippageInterval != 0)
gelatoSlippageInterval = newSlippageInterval;
if (newTreasury != address(0)) managerTreasury = newTreasury;
}
/// @notice initializeManagerFee sets a managerFee, only manager can call.
/// If a manager fee was not set in the initialize function it can be set here
/// but ONLY ONCE- after it is set to a non-zero value, managerFee can never be set again.
/// @param _managerFeeBPS proportion of fees earned that are credited to manager in Basis Points
function initializeManagerFee(uint16 _managerFeeBPS) external onlyManager {
require(managerFeeBPS == 0, "fee");
require(
_managerFeeBPS > 0 && _managerFeeBPS <= 10000 - gelatoFeeBPS,
"mBPS"
);
emit SetManagerFee(_managerFeeBPS);
managerFeeBPS = _managerFeeBPS;
}
function renounceOwnership() public virtual override onlyManager {
managerTreasury = address(0);
managerFeeBPS = 0;
managerBalance0 = 0;
managerBalance1 = 0;
super.renounceOwnership();
}
function getPositionID() external view returns (bytes32 positionID) {
return _getPositionID();
}
function _getPositionID() internal view returns (bytes32 positionID) {
return keccak256(abi.encodePacked(address(this), lowerTick, upperTick));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract Gelatofied {
using Address for address payable;
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
address payable public immutable GELATO;
address private constant _ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(address payable _gelato) {
GELATO = _gelato;
}
modifier gelatofy(uint256 _amount, address _paymentToken) {
require(msg.sender == GELATO, "Gelatofied: Only gelato");
_;
if (_paymentToken == _ETH) GELATO.sendValue(_amount);
else IERC20(_paymentToken).safeTransfer(GELATO, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an manager) that can be granted exclusive access to
* specific functions.
*
* By default, the manager 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
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract OwnableUninitialized {
address internal _manager;
event OwnershipTransferred(
address indexed previousManager,
address indexed newManager
);
/// @dev Initializes the contract setting the deployer as the initial manager.
/// CONSTRUCTOR EMPTY - USE INITIALIZIABLE INSTEAD
// solhint-disable-next-line no-empty-blocks
constructor() {}
/**
* @dev Returns the address of the current manager.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(manager() == msg.sender, "Ownable: caller is not the manager");
_;
}
/**
* @dev Leaves the contract without manager. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current manager.
*
* NOTE: Renouncing ownership will leave the contract without an manager,
* thereby removing any functionality that is only available to the manager.
*/
function renounceOwnership() public virtual onlyManager {
emit OwnershipTransferred(_manager, address(0));
_manager = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current manager.
*/
function transferOwnership(address newOwner) public virtual onlyManager {
require(
newOwner != address(0),
"Ownable: new manager is the zero address"
);
emit OwnershipTransferred(_manager, newOwner);
_manager = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// EDIT for 0.8 compatibility:
// see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import {FullMath} from "./FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate =
FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return
toUint128(
FullMath.mulDiv(
amount0,
intermediate,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
toUint128(
FullMath.mulDiv(
amount1,
FixedPoint96.Q96,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(
sqrtRatioAX96,
sqrtRatioBX96,
amount0
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 =
getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 =
getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioBX96,
amount1
);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount0 The amount0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount1 The amount1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioX96,
sqrtRatioBX96,
liquidity
);
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioX96,
liquidity
);
} else {
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick)
internal
pure
returns (uint160 sqrtPriceX96)
{
uint256 absTick =
tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
// EDIT: 0.8 compatibility
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio =
absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0)
ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0)
ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0)
ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0)
ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0)
ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0)
ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0)
ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0)
ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0)
ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0)
ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0)
ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0)
ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0)
ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0)
ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0)
ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0)
ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0)
ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0)
ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0)
ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160(
(ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
);
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96)
internal
pure
returns (int24 tick)
{
// second inequality must be < because the price can never reach the price at the max tick
require(
sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
"R"
);
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow =
int24(
(log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
);
int24 tickHi =
int24(
(log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
? tickHi
: tickLow;
}
}
| Computes the maximum amount of liquidity received for a given amount of token0, token1, the current pool prices and the prices at the tick boundaries | function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(
sqrtRatioAX96,
sqrtRatioBX96,
amount0
);
uint128 liquidity0 =
getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 =
getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
liquidity = getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioBX96,
amount1
);
}
}
| 454,118 |
./full_match/137/0x11d455366ba5D590e7838c4CEcE9aCC95C567e46/sources/contracts/trove-factory.sol | function to be called from trove to change totalDebt _borrow indicates if it is borrow or repay/liquidatin/ | function updateTotalDebt(uint256 _amount, bool _borrow) public override {
ITrove trove = ITrove(msg.sender);
address token = address(trove.token());
require(containsTrove(token, msg.sender), "fbfd5 not a valid trove");
if (_borrow) {
totalDebt += _amount;
_troves[token].totalDebt += _amount;
totalDebt -= _amount;
_troves[token].totalDebt -= _amount;
}
emit DebtUpdate(token, totalDebt);
}
| 4,722,890 |
./full_match/420/0x5597F952E9aB06D914CFf34f6E26f3D0C0cc5e51/sources/contracts/core/promise/PromiseRouter.sol | Process stored callback function transferId The transferId to process/ parse out the return data and callback address from message enforce relayer is whitelisted by calling local connext contract remove message remove callback fees execute callback Should transfer the stored relayer fee to the msg.sender | function process(bytes32 transferId, bytes calldata _message) public nonReentrant {
bytes32 messageHash = messageHashes[transferId];
if (messageHash == bytes32(0)) revert PromiseRouter__process_invalidTransferId();
bytes29 _msg = _message.ref(0).mustBePromiseCallback();
if (messageHash != _msg.keccak()) revert PromiseRouter__process_invalidMessage();
if (!connext.approvedRelayers(msg.sender)) revert PromiseRouter__process_notApprovedRelayer();
address callbackAddress = _msg.callbackAddress();
if (!AddressUpgradeable.isContract(callbackAddress)) revert PromiseRouter__process_notContractCallback();
uint256 callbackFee = callbackFees[transferId];
delete messageHashes[transferId];
delete callbackFees[transferId];
uint256 gas = gasleft() - RESERVE_GAS;
(bool success, ) = ExcessivelySafeCall.excessivelySafeCall(
callbackAddress,
gas,
MAX_COPY,
abi.encodeWithSelector(ICallback.callback.selector, transferId, _msg.returnSuccess(), _msg.returnData())
);
emit CallbackExecuted(transferId, success, msg.sender);
if (callbackFee != 0) {
AddressUpgradeable.sendValue(payable(msg.sender), callbackFee);
}
}
| 13,226,983 |
pragma solidity >= 0.5.0;
import "./Ownable.sol";
import "./IF_EAS.sol";
import "./IF_EAS_artworks.sol";
import "./IF_EAS_platform.sol";
contract EAS_mission is Ownable{
uint16 public recentRangeOffset = 30;
mapping(uint => address[]) public winners1; // [stageNo] => Mission Winners
mapping(uint => address[]) public winners2; // [stageNo] => Mission Winners
mapping(uint => address[]) public winners3; // [stageNo] => Mission Winners
mapping(uint => mapping(address => uint)) public unclaimedRewards;
mapping(uint => mapping(address => uint)) public winnerTag;
// ex) unclaimedRewards[stageNo][userAddress] = unclaimed amount of reward for userAddress (in Wei)
mapping(uint => uint64[]) public stageTargets;
mapping(uint => uint[]) public stageRewards;
mapping(uint => uint) public stageCutOffId;
mapping(uint=>uint) internal stageTimestamp;
mapping(bytes32=>uint) internal idToStage;
mapping(bytes32=>bool) internal playMissionId; // for oraclize query identification
IF_EAS IFEAS;
IF_EAS_artworks IFEAS_artworks;
IF_EAS_platform IFEAS_platform;
modifier platform() { /* Only EtherArts Platform (EtherArtsOperations contract, EtherArtsStorage contract, Contract owner) can access this contract */
require(IFEAS_platform.accessAllowed(msg.sender) == true, "msg.sender (platform error, EAS_mission");
_;
}
constructor(address _addrEAS, address _addrEAS_artworks, address _addr_EAS_platform) public{
IFEAS = IF_EAS(_addrEAS);
IFEAS_artworks = IF_EAS_artworks(_addrEAS_artworks);
IFEAS_platform = IF_EAS_platform(_addr_EAS_platform);
}
function SetRecentRangeOffset(uint16 _newValue) public onlyOwner{
recentRangeOffset = _newValue;
}
function GetRecentRangeOffset() public view returns (uint16){
return recentRangeOffset;
}
function FinalizeStage(uint _stageNo) public platform{
uint lastIndex = 0;
if(IFEAS_artworks.GetArtworksLength() > 0){
lastIndex = IFEAS_artworks.GetArtworksLength() - 1;
}
stageCutOffId[_stageNo] = IFEAS_artworks.GetArtworksLength() - 1; // final card-id for stage
IFEAS.SetStageNo(_stageNo + 1);
}
function GetStageCutoffId(uint _stageNo) public view returns(uint){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 1");
return stageCutOffId[_stageNo];
}
/***********************************************/
/* MAPPING FOR MISSION INTERFACE */
/***********************************************/
function SetReward(uint _stageNo, address _address, uint _rewardInWei) public platform {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 2");
require(_rewardInWei >= 0, "EAS_MIS, 3");
unclaimedRewards[_stageNo][_address] = _rewardInWei;
if(_rewardInWei > 0){
winnerTag[_stageNo][_address] = _rewardInWei;
}
}
function GetUserRewards(address _Owner) public view returns(uint[] memory){
require(msg.sender == _Owner, "EAS_MIS, 3");
uint numStages = IFEAS.stageNo();
uint[] memory rewards = new uint[](numStages);
for(uint i=0; i<numStages; i++){
rewards[i] = unclaimedRewards[i][_Owner];
}
return rewards;
}
/*
function GetUserWinnerTag(uint _stageNo, address _address) public view returns(uint){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "StageNo RangeErr, GetUserStageReward");
return(winnerTag[_stageNo][_address]);
}
*/
function GetUserStageReward(uint _stageNo, address _address) public view returns(uint){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 4");
return(unclaimedRewards[_stageNo][_address]);
}
function SetStageRewards(uint _stageNo, uint _reward1, uint _reward2, uint _reward3) public platform{
// need to add some protection here
stageRewards[_stageNo].push(_reward1);
stageRewards[_stageNo].push(_reward2);
stageRewards[_stageNo].push(_reward3);
}
/*
function GetStageRewards(uint _stageNo) public view returns (uint, uint){
require(stageRewards[_stageNo].length == 2, "EAS_MIS, 5");
return(stageRewards[_stageNo][0], stageRewards[_stageNo][1]);
}
*/
function GetStageRewardsHistory() public view returns (uint[] memory, uint[] memory, uint[] memory){
uint stages = IFEAS.stageNo();
uint[] memory reward1 = new uint[](stages);
uint[] memory reward2 = new uint[](stages);
uint[] memory reward3 = new uint[](stages);
for(uint i=0; i<stages; i++){
reward1[i] = stageRewards[i][0]; // reward history for single 1st winners
reward2[i] = stageRewards[i][1]; // reward history for single 2nd winners, (card type1 only)
reward3[i] = stageRewards[i][2]; // reward history for single 2nd winners, (card type2 only)
}
return(reward1, reward2, reward3);
}
function SetPlayMissionId(bytes32 _id, bool _val) external platform{
playMissionId[_id] = _val;
}
function GetPlayMissionId(bytes32 _id) public view returns(bool){
return playMissionId[_id];
}
function SetStageTargets(uint _stageNo, uint64 num1, uint64 num2) external platform{
require(_stageNo == IFEAS.stageNo(), "EAS_MIS, 6");
require(stageTargets[_stageNo].length == 0, "EAS_MIS, 7");
stageTargets[_stageNo].push(num1);
stageTargets[_stageNo].push(num2);
}
/*
function GetStageTargets(uint _stageNo) view public returns(uint64, uint64) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 10");
if(stageTargets[_stageNo].length == 2){
return(stageTargets[_stageNo][0], stageTargets[_stageNo][1]);
}else{
return(0, 0);
}
}
*/
function AppendWinner1(uint _stageNo, address _winner) external platform{
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 11");
if(IsNewWinner1(_stageNo, _winner)){
winners1[_stageNo].push(_winner);
}
}
function IsNewWinner1(uint _stageNo, address _newAddr) view public returns(bool){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 12");
uint lenth = GetWinner1Length(_stageNo);
for(uint i=0; i<lenth; i++){
if(winners1[_stageNo][i] == _newAddr){
return false;
}
}
return true;
}
function GetWinner1Length(uint _stageNo) view public returns(uint) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 13");
return winners1[_stageNo].length;
}
function GetWinner1(uint _stageNo, uint _idx) view public returns(address) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 14");
return winners1[_stageNo][_idx];
}
function AppendWinner2(uint _stageNo, address _winner) external platform{
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 21");
if(IsNewWinner2(_stageNo, _winner)){
winners2[_stageNo].push(_winner);
}
}
function IsNewWinner2(uint _stageNo, address _newAddr) view public returns(bool){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 22");
uint lenth = GetWinner2Length(_stageNo);
for(uint i=0; i<lenth; i++){
if(winners2[_stageNo][i] == _newAddr){
return false;
}
}
return true;
}
function GetWinner2Length(uint _stageNo) view public returns(uint) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 23");
return winners2[_stageNo].length;
}
function GetWinner2(uint _stageNo, uint _idx) view public returns(address) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 24");
return winners2[_stageNo][_idx];
}
function AppendWinner3(uint _stageNo, address _winner) external platform{
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 31");
if(IsNewWinner3(_stageNo, _winner)){
winners3[_stageNo].push(_winner);
}
}
function IsNewWinner3(uint _stageNo, address _newAddr) view public returns(bool){
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 32");
uint lenth = GetWinner3Length(_stageNo);
for(uint i=0; i<lenth; i++){
if(winners3[_stageNo][i] == _newAddr){
return false;
}
}
return true;
}
function GetWinner3Length(uint _stageNo) view public returns(uint) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 33");
return winners3[_stageNo].length;
}
function GetWinner3(uint _stageNo, uint _idx) view public returns(address) {
require(_stageNo <= IFEAS.stageNo() && _stageNo >= 0, "EAS_MIS, 34");
return winners3[_stageNo][_idx];
}
function GetIdToStage(bytes32 _id) public view returns (uint){
return idToStage[_id];
}
function SetIdToStage(bytes32 _id, uint _stageNo) external platform{
idToStage[_id] = _stageNo;
}
} | need to add some protection here | function SetStageRewards(uint _stageNo, uint _reward1, uint _reward2, uint _reward3) public platform{
stageRewards[_stageNo].push(_reward1);
stageRewards[_stageNo].push(_reward2);
stageRewards[_stageNo].push(_reward3);
}
| 982,055 |
pragma solidity 0.4.23;
// File: mixbytes-solidity/contracts/security/ArgumentsChecker.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
pragma solidity ^0.4.15;
/// @title utility methods and modifiers of arguments validation
contract ArgumentsChecker {
/// @dev check which prevents short address attack
modifier payloadSizeIs(uint size) {
require(msg.data.length == size + 4 /* function selector */);
_;
}
/// @dev check that address is valid
modifier validAddress(address addr) {
require(addr != address(0));
_;
}
}
// File: mixbytes-solidity/contracts/crowdsale/FixedTimeBonuses.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
pragma solidity ^0.4.15;
library FixedTimeBonuses {
struct Bonus {
uint endTime;
uint bonus;
}
struct Data {
Bonus[] bonuses;
}
/// @dev validates consistency of data structure
/// @param self data structure
/// @param shouldDecrease additionally check if bonuses are decreasing over time
function validate(Data storage self, bool shouldDecrease) internal constant {
uint length = self.bonuses.length;
require(length > 0);
Bonus storage last = self.bonuses[0];
for (uint i = 1; i < length; i++) {
Bonus storage current = self.bonuses[i];
require(current.endTime > last.endTime);
if (shouldDecrease)
require(current.bonus < last.bonus);
last = current;
}
}
/// @dev get ending time of the last bonus
/// @param self data structure
function getLastTime(Data storage self) internal constant returns (uint) {
return self.bonuses[self.bonuses.length - 1].endTime;
}
/// @dev validates consistency of data structure
/// @param self data structure
/// @param time time for which bonus must be computed (assuming time <= getLastTime())
function getBonus(Data storage self, uint time) internal constant returns (uint) {
// TODO binary search?
uint length = self.bonuses.length;
for (uint i = 0; i < length; i++) {
if (self.bonuses[i].endTime >= time)
return self.bonuses[i].bonus;
}
assert(false); // must be unreachable
}
}
// File: zeppelin-solidity/contracts/ReentrancyGuard.sol
/**
* @title Helps contracts guard agains rentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
// File: contracts/oraclize/usingOraclize.sol
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
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.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: mixbytes-solidity/contracts/ownership/multiowned.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
// Code taken from https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol
// Audit, refactoring and improvements by github.com/Eenae
// @authors:
// Gav Wood <[email protected]>
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
pragma solidity ^0.4.15;
/// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled
// TODO acceptOwnership
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct MultiOwnedOperationPendingState {
// count of confirmations needed
uint yetNeeded;
// bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit
uint ownersDone;
// position of this operation key in m_multiOwnedPendingIndex
uint index;
}
// EVENTS
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
event FinalConfirmation(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
require(isOwner(msg.sender));
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
// Even if required number of confirmations has't been collected yet,
// we can't throw here - because changes to the state have to be preserved.
// But, confirmAndCheck itself will throw in case sender is not an owner.
}
modifier validNumOwners(uint _numOwners) {
require(_numOwners > 0 && _numOwners <= c_maxOwners);
_;
}
modifier multiOwnedValidRequirement(uint _required, uint _numOwners) {
require(_required > 0 && _required <= _numOwners);
_;
}
modifier ownerExists(address _address) {
require(isOwner(_address));
_;
}
modifier ownerDoesNotExist(address _address) {
require(!isOwner(_address));
_;
}
modifier multiOwnedOperationIsActive(bytes32 _operation) {
require(isOperationActive(_operation));
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).
function multiowned(address[] _owners, uint _required)
public
validNumOwners(_owners.length)
multiOwnedValidRequirement(_required, _owners.length)
{
assert(c_maxOwners <= 255);
m_numOwners = _owners.length;
m_multiOwnedRequired = _required;
for (uint i = 0; i < _owners.length; ++i)
{
address owner = _owners[i];
// invalid and duplicate addresses are not allowed
require(0 != owner && !isOwner(owner) /* not isOwner yet! */);
uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);
m_owners[currentOwnerIndex] = owner;
m_ownerIndex[owner] = currentOwnerIndex;
}
assertOwnersAreConsistent();
}
/// @notice replaces an owner `_from` with another `_to`.
/// @param _from address of owner to replace
/// @param _to address of new owner
// All pending operations will be canceled!
function changeOwner(address _from, address _to)
external
ownerExists(_from)
ownerDoesNotExist(_to)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]);
m_owners[ownerIndex] = _to;
m_ownerIndex[_from] = 0;
m_ownerIndex[_to] = ownerIndex;
assertOwnersAreConsistent();
OwnerChanged(_from, _to);
}
/// @notice adds an owner
/// @param _owner address of new owner
// All pending operations will be canceled!
function addOwner(address _owner)
external
ownerDoesNotExist(_owner)
validNumOwners(m_numOwners + 1)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
m_numOwners++;
m_owners[m_numOwners] = _owner;
m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners);
assertOwnersAreConsistent();
OwnerAdded(_owner);
}
/// @notice removes an owner
/// @param _owner address of owner to remove
// All pending operations will be canceled!
function removeOwner(address _owner)
external
ownerExists(_owner)
validNumOwners(m_numOwners - 1)
multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);
m_owners[ownerIndex] = 0;
m_ownerIndex[_owner] = 0;
//make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners();
assertOwnersAreConsistent();
OwnerRemoved(_owner);
}
/// @notice changes the required number of owner signatures
/// @param _newRequired new number of signatures required
// All pending operations will be canceled!
function changeRequirement(uint _newRequired)
external
multiOwnedValidRequirement(_newRequired, m_numOwners)
onlymanyowners(keccak256(msg.data))
{
m_multiOwnedRequired = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
/// @notice Gets an owner by 0-indexed position
/// @param ownerIndex 0-indexed owner position
function getOwner(uint ownerIndex) public constant returns (address) {
return m_owners[ownerIndex + 1];
}
/// @notice Gets owners
/// @return memory array of owners
function getOwners() public constant returns (address[]) {
address[] memory result = new address[](m_numOwners);
for (uint i = 0; i < m_numOwners; i++)
result[i] = getOwner(i);
return result;
}
/// @notice checks if provided address is an owner address
/// @param _addr address to check
/// @return true if it's an owner
function isOwner(address _addr) public constant returns (bool) {
return m_ownerIndex[_addr] > 0;
}
/// @notice Tests ownership of the current caller.
/// @return true if it's an owner
// It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to
// addOwner/changeOwner and to isOwner.
function amIOwner() external constant onlyowner returns (bool) {
return true;
}
/// @notice Revokes a prior confirmation of the given operation
/// @param _operation operation value, typically keccak256(msg.data)
function revoke(bytes32 _operation)
external
multiOwnedOperationIsActive(_operation)
onlyowner
{
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
var pending = m_multiOwnedPending[_operation];
require(pending.ownersDone & ownerIndexBit > 0);
assertOperationIsConsistent(_operation);
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
assertOperationIsConsistent(_operation);
Revoke(msg.sender, _operation);
}
/// @notice Checks if owner confirmed given operation
/// @param _operation operation value, typically keccak256(msg.data)
/// @param _owner an owner address
function hasConfirmed(bytes32 _operation, address _owner)
external
constant
multiOwnedOperationIsActive(_operation)
ownerExists(_owner)
returns (bool)
{
return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation)
private
onlyowner
returns (bool)
{
if (512 == m_multiOwnedPendingIndex.length)
// In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point
// we won't be able to do it because of block gas limit.
// Yes, pending confirmations will be lost. Dont see any security or stability implications.
// TODO use more graceful approach like compact or removal of clearPending completely
clearPending();
var pending = m_multiOwnedPending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (! isOperationActive(_operation)) {
// reset count of confirmations needed.
pending.yetNeeded = m_multiOwnedRequired;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_multiOwnedPendingIndex.length++;
m_multiOwnedPendingIndex[pending.index] = _operation;
assertOperationIsConsistent(_operation);
}
// determine the bit to set for this owner.
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
// ok - check if count is enough to go ahead.
assert(pending.yetNeeded > 0);
if (pending.yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index];
delete m_multiOwnedPending[_operation];
FinalConfirmation(msg.sender, _operation);
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
assertOperationIsConsistent(_operation);
Confirmation(msg.sender, _operation);
}
}
}
// Reclaims free slots between valid owners in m_owners.
// TODO given that its called after each removal, it could be simplified.
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
// iterating to the first free slot from the beginning
while (free < m_numOwners && m_owners[free] != 0) free++;
// iterating to the first occupied slot from the end
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
// swap, if possible, so free slot is located at the end after the swap
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
// owners between swapped slots should't be renumbered - that saves a lot of gas
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() private onlyowner {
uint length = m_multiOwnedPendingIndex.length;
// TODO block gas limit
for (uint i = 0; i < length; ++i) {
if (m_multiOwnedPendingIndex[i] != 0)
delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]];
}
delete m_multiOwnedPendingIndex;
}
function checkOwnerIndex(uint ownerIndex) private pure returns (uint) {
assert(0 != ownerIndex && ownerIndex <= c_maxOwners);
return ownerIndex;
}
function makeOwnerBitmapBit(address owner) private constant returns (uint) {
uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]);
return 2 ** ownerIndex;
}
function isOperationActive(bytes32 _operation) private constant returns (bool) {
return 0 != m_multiOwnedPending[_operation].yetNeeded;
}
function assertOwnersAreConsistent() private constant {
assert(m_numOwners > 0);
assert(m_numOwners <= c_maxOwners);
assert(m_owners[0] == 0);
assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners);
}
function assertOperationIsConsistent(bytes32 _operation) private constant {
var pending = m_multiOwnedPending[_operation];
assert(0 != pending.yetNeeded);
assert(m_multiOwnedPendingIndex[pending.index] == _operation);
assert(pending.yetNeeded <= m_multiOwnedRequired);
}
// FIELDS
uint constant c_maxOwners = 250;
// the number of owners that must confirm the same operation before it is run.
uint public m_multiOwnedRequired;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners (addresses),
// slot 0 is unused so there are no owner which index is 0.
// TODO could we save space at the end of the array for the common case of <10 owners? and should we?
address[256] internal m_owners;
// index on the list of owners to allow reverse lookup: owner address => index in m_owners
mapping(address => uint) internal m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending;
bytes32[] internal m_multiOwnedPendingIndex;
}
// File: contracts/EthPriceDependent.sol
contract EthPriceDependent is usingOraclize, multiowned {
using SafeMath for uint256;
event NewOraclizeQuery(string description);
event NewETHPrice(uint price);
event ETHPriceOutOfBounds(uint price);
/// @notice Constructor
/// @param _initialOwners set owners, which can control bounds and things
/// described in the actual sale contract, inherited from this one
/// @param _consensus Number of votes enough to make a decision
/// @param _production True if on mainnet and testnet
function EthPriceDependent(address[] _initialOwners, uint _consensus, bool _production)
public
multiowned(_initialOwners, _consensus)
{
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
if (!_production) {
// Use it when testing with testrpc and etherium bridge. Don't forget to change address
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
} else {
// Don't call this while testing as it's too long and gets in the way
updateETHPriceInCents();
}
}
/// @notice Send oraclize query.
/// if price is received successfully - update scheduled automatically,
/// if at any point the contract runs out of ether - updating stops and further
/// updating will require running this function again.
/// if price is out of bounds - updating attempts continue
function updateETHPriceInCents() public payable {
// prohibit running multiple instances of update
// however don't throw any error, because it's called from __callback as well
// and we need to let it update the price anyway, otherwise there is an attack possibility
if ( !updateRequestExpired() ) {
NewOraclizeQuery("Oraclize request fail. Previous one still pending");
} else if (oraclize_getPrice("URL") > this.balance) {
NewOraclizeQuery("Oraclize request fail. Not enough ether");
} else {
oraclize_query(
m_ETHPriceUpdateInterval,
"URL",
"json(https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD).0.price_usd",
m_callbackGas
);
m_ETHPriceLastUpdateRequest = getTime();
NewOraclizeQuery("Oraclize query was sent");
}
}
/// @notice Called on ETH price update by Oraclize
function __callback(bytes32 myid, string result, bytes proof) public {
require(msg.sender == oraclize_cbAddress());
uint newPrice = parseInt(result).mul(100);
if (newPrice >= m_ETHPriceLowerBound && newPrice <= m_ETHPriceUpperBound) {
m_ETHPriceInCents = newPrice;
m_ETHPriceLastUpdate = getTime();
NewETHPrice(m_ETHPriceInCents);
} else {
ETHPriceOutOfBounds(newPrice);
}
// continue updating anyway (if current price was out of bounds, the price might recover in the next cycle)
updateETHPriceInCents();
}
/// @notice set the limit of ETH in cents, oraclize data greater than this is not accepted
/// @param _price Price in US cents
function setETHPriceUpperBound(uint _price)
external
onlymanyowners(keccak256(msg.data))
{
m_ETHPriceUpperBound = _price;
}
/// @notice set the limit of ETH in cents, oraclize data smaller than this is not accepted
/// @param _price Price in US cents
function setETHPriceLowerBound(uint _price)
external
onlymanyowners(keccak256(msg.data))
{
m_ETHPriceLowerBound = _price;
}
/// @notice set the price of ETH in cents, called in case we don't get oraclize data
/// for more than double the update interval
/// @param _price Price in US cents
function setETHPriceManually(uint _price)
external
onlymanyowners(keccak256(msg.data))
{
// allow for owners to change the price anytime if update is not running
// but if it is, then only in case the price has expired
require( priceExpired() || updateRequestExpired() );
m_ETHPriceInCents = _price;
m_ETHPriceLastUpdate = getTime();
NewETHPrice(m_ETHPriceInCents);
}
/// @notice add more ether to use in oraclize queries
function topUp() external payable {
}
/// @dev change gas price for oraclize calls,
/// should be a compromise between speed and price according to market
/// @param _gasPrice gas price in wei
function setOraclizeGasPrice(uint _gasPrice)
external
onlymanyowners(keccak256(msg.data))
{
oraclize_setCustomGasPrice(_gasPrice);
}
/// @dev change gas limit for oraclize callback
/// note: should be changed only in case of emergency
/// @param _callbackGas amount of gas
function setOraclizeGasLimit(uint _callbackGas)
external
onlymanyowners(keccak256(msg.data))
{
m_callbackGas = _callbackGas;
}
/// @dev Check that double the update interval has passed
/// since last successful price update
function priceExpired() public view returns (bool) {
return (getTime() > m_ETHPriceLastUpdate + 2 * m_ETHPriceUpdateInterval);
}
/// @dev Check that price update was requested
/// more than 1 update interval ago
/// NOTE: m_leeway seconds added to offset possible timestamp inaccuracy
function updateRequestExpired() public view returns (bool) {
return ( (getTime() + m_leeway) >= (m_ETHPriceLastUpdateRequest + m_ETHPriceUpdateInterval) );
}
/// @dev to be overridden in tests
function getTime() internal view returns (uint) {
return now;
}
// FIELDS
/// @notice usd price of ETH in cents, retrieved using oraclize
uint public m_ETHPriceInCents = 0;
/// @notice unix timestamp of last update
uint public m_ETHPriceLastUpdate;
/// @notice unix timestamp of last update request,
/// don't allow requesting more than once per update interval
uint public m_ETHPriceLastUpdateRequest;
/// @notice lower bound of the ETH price in cents
uint public m_ETHPriceLowerBound = 100;
/// @notice upper bound of the ETH price in cents
uint public m_ETHPriceUpperBound = 100000000;
/// @dev Update ETH price in cents every 12 hours
uint public m_ETHPriceUpdateInterval = 60*60*1;
/// @dev offset time inaccuracy when checking update expiration date
uint public m_leeway = 900; // 15 minutes is the limit for miners
/// @dev set just enough gas because the rest is not refunded
uint public m_callbackGas = 200000;
}
// File: contracts/EthPriceDependentForICO.sol
contract EthPriceDependentForICO is EthPriceDependent {
/// @dev overridden price lifetime logic
function priceExpired() public view returns (bool) {
return 0 == m_ETHPriceInCents;
}
}
// File: mixbytes-solidity/contracts/ownership/MultiownedControlled.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
pragma solidity ^0.4.15;
/**
* @title Contract which is owned by owners and operated by controller.
*
* @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
* @dev controller check is performed by onlyController modifier.
*/
contract MultiownedControlled is multiowned {
event ControllerSet(address controller);
event ControllerRetired(address was);
event ControllerRetiredForever(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
// PUBLIC interface
function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller)
public
multiowned(_owners, _signaturesRequired)
{
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev sets the controller
function setController(address _controller) external onlymanyowners(keccak256(msg.data)) {
require(m_attaching_enabled);
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev ability for controller to step down
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
/// @dev ability for controller to step down and make this contract completely automatic (without third-party control)
function detachControllerForever() external onlyController {
assert(m_attaching_enabled);
address was = m_controller;
m_controller = address(0);
m_attaching_enabled = false;
ControllerRetiredForever(was);
}
// FIELDS
/// @notice address of entity entitled to mint new tokens
address public m_controller;
bool public m_attaching_enabled = true;
}
// File: contracts/IBoomstarterToken.sol
/// @title Interface of the BoomstarterToken.
interface IBoomstarterToken {
// multiowned
function changeOwner(address _from, address _to) external;
function addOwner(address _owner) external;
function removeOwner(address _owner) external;
function changeRequirement(uint _newRequired) external;
function getOwner(uint ownerIndex) public view returns (address);
function getOwners() public view returns (address[]);
function isOwner(address _addr) public view returns (bool);
function amIOwner() external view returns (bool);
function revoke(bytes32 _operation) external;
function hasConfirmed(bytes32 _operation, address _owner) external view returns (bool);
// ERC20Basic
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
// ERC20
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);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
// BurnableToken
function burn(uint256 _amount) public returns (bool);
// TokenWithApproveAndCallMethod
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public;
// BoomstarterToken
function setSale(address account, bool isSale) external;
function switchToNextSale(address _newSale) external;
function thaw() external;
function disablePrivileged() external;
}
// File: contracts/crowdsale/FundsRegistry.sol
/// @title registry of funds sent by investors
contract FundsRegistry is ArgumentsChecker, MultiownedControlled, ReentrancyGuard {
using SafeMath for uint256;
enum State {
// gathering funds
GATHERING,
// returning funds to investors
REFUNDING,
// funds can be pulled by owners
SUCCEEDED
}
event StateChanged(State _state);
event Invested(address indexed investor, uint etherInvested, uint tokensReceived);
event EtherSent(address indexed to, uint value);
event RefundSent(address indexed to, uint value);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
// PUBLIC interface
function FundsRegistry(
address[] _owners,
uint _signaturesRequired,
address _controller,
address _token
)
MultiownedControlled(_owners, _signaturesRequired, _controller)
{
m_token = IBoomstarterToken(_token);
}
/// @dev performs only allowed state transitions
function changeState(State _newState)
external
onlyController
{
assert(m_state != _newState);
if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); }
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
/// @dev records an investment
/// @param _investor who invested
/// @param _tokenAmount the amount of token bought, calculation is handled by ICO
function invested(address _investor, uint _tokenAmount)
external
payable
onlyController
requiresState(State.GATHERING)
{
uint256 amount = msg.value;
require(0 != amount);
assert(_investor != m_controller);
// register investor
if (0 == m_weiBalances[_investor])
m_investors.push(_investor);
// register payment
totalInvested = totalInvested.add(amount);
m_weiBalances[_investor] = m_weiBalances[_investor].add(amount);
m_tokenBalances[_investor] = m_tokenBalances[_investor].add(_tokenAmount);
Invested(_investor, amount, _tokenAmount);
}
/// @notice owners: send `value` of ether to address `to`, can be called if crowdsale succeeded
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
validAddress(to)
onlymanyowners(keccak256(msg.data))
requiresState(State.SUCCEEDED)
{
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
/// @notice owners: send `value` of tokens to address `to`, can be called if
/// crowdsale failed and some of the investors refunded the ether
/// @param to where to send tokens
/// @param value amount of token-wei to send
function sendTokens(address to, uint value)
external
validAddress(to)
onlymanyowners(keccak256(msg.data))
requiresState(State.REFUNDING)
{
require(value > 0 && m_token.balanceOf(this) >= value);
m_token.transfer(to, value);
}
/// @notice withdraw accumulated balance, called by payee in case crowdsale failed
/// @dev caller should approve tokens bought during ICO to this contract
function withdrawPayments()
external
nonReentrant
requiresState(State.REFUNDING)
{
address payee = msg.sender;
uint payment = m_weiBalances[payee];
uint tokens = m_tokenBalances[payee];
// check that there is some ether to withdraw
require(payment != 0);
// check that the contract holds enough ether
require(this.balance >= payment);
// check that the investor (payee) gives back all tokens bought during ICO
require(m_token.allowance(payee, this) >= m_tokenBalances[payee]);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
m_tokenBalances[payee] = 0;
m_token.transferFrom(payee, this, tokens);
payee.transfer(payment);
RefundSent(payee, payment);
}
function getInvestorsCount() external constant returns (uint) { return m_investors.length; }
// FIELDS
/// @notice total amount of investments in wei
uint256 public totalInvested;
/// @notice state of the registry
State public m_state = State.GATHERING;
/// @dev balances of investors in wei
mapping(address => uint256) public m_weiBalances;
/// @dev balances of tokens sold to investors
mapping(address => uint256) public m_tokenBalances;
/// @dev list of unique investors
address[] public m_investors;
/// @dev token accepted for refunds
IBoomstarterToken public m_token;
}
// File: minter-service/contracts/IICOInfo.sol
contract IICOInfo {
function estimate(uint256 _wei) public constant returns (uint tokens);
function purchasedTokenBalanceOf(address addr) public constant returns (uint256 tokens);
function isSaleActive() public constant returns (bool active);
}
// File: minter-service/contracts/IMintableToken.sol
contract IMintableToken {
function mint(address _to, uint256 _amount);
}
// File: contracts/BoomstarterSale.sol
contract BoomstarterSale is ArgumentsChecker, ReentrancyGuard, EthPriceDependentForICO, IICOInfo, IMintableToken {
using FixedTimeBonuses for FixedTimeBonuses.Data;
enum IcoState { INIT, ACTIVE, PAUSED, FAILED, SUCCEEDED }
event StateChanged(IcoState _state);
event FundTransfer(address backer, uint amount, bool isContribution);
modifier requiresState(IcoState _state) {
require(m_state == _state);
_;
}
/// @dev triggers some state changes based on current time
/// @param client optional refund parameter
/// @param payment optional refund parameter
/// @param refundable - if false, payment is made off-chain and shouldn't be refunded
/// note: function body could be skipped!
modifier timedStateChange(address client, uint payment, bool refundable) {
if (IcoState.INIT == m_state && getTime() >= getStartTime())
changeState(IcoState.ACTIVE);
if (IcoState.ACTIVE == m_state && getTime() >= getFinishTime()) {
finishICOInternal();
if (refundable && payment > 0)
client.transfer(payment);
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
}
}
/// @dev automatic check for unaccounted withdrawals
/// @param client optional refund parameter
/// @param payment optional refund parameter
/// @param refundable - if false, payment is made off-chain and shouldn't be refunded
modifier fundsChecker(address client, uint payment, bool refundable) {
uint atTheBeginning = m_funds.balance;
if (atTheBeginning < m_lastFundsAmount) {
changeState(IcoState.PAUSED);
if (refundable && payment > 0)
client.transfer(payment); // we cant throw (have to save state), so refunding this way
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
if (m_funds.balance < atTheBeginning) {
changeState(IcoState.PAUSED);
} else {
m_lastFundsAmount = m_funds.balance;
}
}
}
function estimate(uint256 _wei) public view returns (uint tokens) {
uint amount;
(amount, ) = estimateTokensWithActualPayment(_wei);
return amount;
}
function isSaleActive() public view returns (bool active) {
return m_state == IcoState.ACTIVE && !priceExpired();
}
function purchasedTokenBalanceOf(address addr) public view returns (uint256 tokens) {
return m_token.balanceOf(addr);
}
function getTokenBonus() public view returns (uint percent) {
if (getTime() < 1538341200) // OCT 1
return 0;
if (getTime() >= getFinishTime())
return 0;
return m_tokenBonuses.getBonus(getTime());
}
function ether2tokens(uint ether_) public view returns (uint) {
return ether_.mul(m_ETHPriceInCents).div(c_tokenPriceInCents).mul(getTokenBonus().add(100)).div(100);
}
function tokens2ether(uint tokens) public view returns (uint) {
return tokens.mul(100).div(getTokenBonus().add(100)).mul(c_tokenPriceInCents).div(m_ETHPriceInCents);
}
function estimateTokensWithActualPayment(uint256 _payment) public view returns (uint amount, uint actualPayment) {
// amount of bought tokens
uint tokens = ether2tokens(_payment);
if (tokens.add(m_currentTokensSold) > c_maximumTokensSold) {
tokens = c_maximumTokensSold.sub( m_currentTokensSold );
_payment = tokens2ether(tokens);
}
return (tokens, _payment);
}
// PUBLIC interface
/**
* @dev constructor
* @param _owners addresses to do administrative actions
* @param _token address of token being sold
* @param _updateInterval time between oraclize price updates in seconds
* @param _production false if using testrpc/ganache, true otherwise
*/
constructor(
address[] _owners,
address _token,
uint _updateInterval,
bool _production
)
public
payable
EthPriceDependent(_owners, 2, _production)
validAddress(_token)
{
require(3 == _owners.length);
m_token = IBoomstarterToken(_token);
m_ETHPriceUpdateInterval = _updateInterval;
m_startTime = getTime();
oraclize_setCustomGasPrice(40*1000*1000*1000);
m_tokenBonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1538946000 - 1, bonus: 25})); // up to OCT 8
m_tokenBonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1539550800 - 1, bonus: 15})); // up to OCT 15
m_tokenBonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1540155600 - 1, bonus: 10})); // up to OCT 22
m_tokenBonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1541019600 - 1, bonus: 5})); // up to NOV 1
m_tokenBonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1853960400 - 1, bonus: 0})); // up to 2028 OCT 1
m_tokenBonuses.validate(true);
}
/// @dev set addresses for ether and token storage
/// performed once by deployer
/// @param _funds FundsRegistry address
/// @param _tokenDistributor address to send remaining tokens to after ICO
function init(address _funds, address _tokenDistributor)
external
validAddress(_funds)
validAddress(_tokenDistributor)
onlymanyowners(keccak256(msg.data))
{
require(m_token.balanceOf(this) > 0); // tokens must be transferred beforehand
// can be set only once
require(m_funds == address(0));
m_funds = FundsRegistry(_funds);
// calculate remaining tokens and leave 25% for manual allocation
c_maximumTokensSold = m_token.balanceOf(this).sub( m_token.totalSupply().div(4) );
// set account that allocates the rest of tokens after ico succeeds
m_tokenDistributor = _tokenDistributor;
}
// PUBLIC interface: payments
// fallback function as a shortcut
function() payable {
require(0 == msg.data.length);
buy(); // only internal call here!
}
/// @notice ICO participation
function buy() public payable { // dont mark as external!
internalBuy(msg.sender, msg.value, true);
}
function mint(address client, uint256 ethers) public {
nonEtherBuy(client, ethers);
}
/// @notice register investments coming in different currencies
/// @dev can only be called by a special controller account
/// @param client Account to send tokens to
/// @param etherEquivalentAmount Amount of ether to use to calculate token amount
function nonEtherBuy(address client, uint etherEquivalentAmount)
public
{
require(msg.sender == m_nonEtherController);
// just to check for input errors
require(etherEquivalentAmount <= 70000 ether);
internalBuy(client, etherEquivalentAmount, false);
}
/// @dev common buy for ether and non-ether
/// @param client who invests
/// @param payment how much ether
/// @param refundable true if invested in ether - using buy()
function internalBuy(address client, uint payment, bool refundable)
internal
nonReentrant
timedStateChange(client, payment, refundable)
fundsChecker(client, payment, refundable)
{
// don't allow to buy anything if price change was too long ago
// effectively enforcing a sale pause
require( !priceExpired() );
require(m_state == IcoState.ACTIVE || m_state == IcoState.INIT && isOwner(client) /* for final test */);
require((payment.mul(m_ETHPriceInCents)).div(1 ether) >= c_MinInvestmentInCents);
uint actualPayment = payment;
uint tokens;
(tokens, actualPayment) = estimateTokensWithActualPayment(payment);
// change ICO investment stats
m_currentTokensSold = m_currentTokensSold.add(tokens);
// send bought tokens to the client
m_token.transfer(client, tokens);
assert(m_currentTokensSold <= c_maximumTokensSold);
if (refundable) {
// record payment if paid in ether
m_funds.invested.value(actualPayment)(client, tokens);
emit FundTransfer(client, actualPayment, true);
}
// check if ICO must be closed early
if (payment.sub(actualPayment) > 0) {
assert(c_maximumTokensSold == m_currentTokensSold);
finishICOInternal();
// send change
client.transfer(payment.sub(actualPayment));
} else if (c_maximumTokensSold == m_currentTokensSold) {
finishICOInternal();
}
}
// PUBLIC interface: misc getters
/// @notice start time of the ICO
function getStartTime() public view returns (uint) {
return m_startTime;
}
/// @notice finish time of the ICO
function getFinishTime() public view returns (uint) {
return m_tokenBonuses.getLastTime();
}
// PUBLIC interface: owners: maintenance
/// @notice pauses ICO
function pause()
external
timedStateChange(address(0), 0, true)
requiresState(IcoState.ACTIVE)
onlyowner
{
changeState(IcoState.PAUSED);
}
/// @notice resume paused ICO
function unpause()
external
timedStateChange(address(0), 0, true)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
changeState(IcoState.ACTIVE);
checkTime();
}
/// @notice withdraw tokens if ico failed
/// @param _to address to send tokens to
/// @param _amount amount of tokens in token-wei
function withdrawTokens(address _to, uint _amount)
external
validAddress(_to)
requiresState(IcoState.FAILED)
onlymanyowners(keccak256(msg.data))
{
require((_amount > 0) && (m_token.balanceOf(this) >= _amount));
m_token.transfer(_to, _amount);
}
/// @notice In case we need to attach to existent funds
function setFundsRegistry(address _funds)
external
validAddress(_funds)
timedStateChange(address(0), 0, true)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
m_funds = FundsRegistry(_funds);
}
/// @notice set non ether investment controller
function setNonEtherController(address _controller)
external
validAddress(_controller)
timedStateChange(address(0), 0, true)
onlymanyowners(keccak256(msg.data))
{
m_nonEtherController = _controller;
}
function getNonEtherController()
public
view
returns (address)
{
return m_nonEtherController;
}
/// @notice explicit trigger for timed state changes
function checkTime()
public
timedStateChange(address(0), 0, true)
onlyowner
{
}
/// @notice send everything to the new (fixed) ico smart contract
/// @param newICO address of the new smart contract
function applyHotFix(address newICO)
public
validAddress(newICO)
requiresState(IcoState.PAUSED)
onlymanyowners(keccak256(msg.data))
{
EthPriceDependent next = EthPriceDependent(newICO);
next.topUp.value(address(this).balance)();
m_token.transfer(newICO, m_token.balanceOf(this));
m_token.switchToNextSale(newICO);
}
/// @notice withdraw all ether for oraclize payments
/// @param to Address to send ether to
function withdrawEther(address to)
public
validAddress(to)
onlymanyowners(keccak256(msg.data))
{
to.transfer(address(this).balance);
}
/// @notice finishes ICO
function finishICO()
public
timedStateChange(address(0), 0, true)
requiresState(IcoState.ACTIVE)
onlymanyowners(keccak256(msg.data))
{
finishICOInternal();
}
// INTERNAL functions
function finishICOInternal() private {
changeState(IcoState.SUCCEEDED);
}
/// @dev performs only allowed state transitions
function changeState(IcoState _newState) private {
assert(m_state != _newState);
if (IcoState.INIT == m_state) {
assert(IcoState.ACTIVE == _newState);
} else if (IcoState.ACTIVE == m_state) {
assert(
IcoState.PAUSED == _newState ||
IcoState.FAILED == _newState ||
IcoState.SUCCEEDED == _newState
);
} else if (IcoState.PAUSED == m_state) {
assert(IcoState.ACTIVE == _newState || IcoState.FAILED == _newState);
} else {
assert(false);
}
m_state = _newState;
emit StateChanged(m_state);
// this should be tightly linked
if (IcoState.SUCCEEDED == m_state) {
onSuccess();
} else if (IcoState.FAILED == m_state) {
onFailure();
}
}
function onSuccess() private {
// allow owners to withdraw collected ether
m_funds.changeState(FundsRegistry.State.SUCCEEDED);
m_funds.detachController();
// send all remaining tokens to the address responsible for dividing them into pools
m_token.transfer(m_tokenDistributor, m_token.balanceOf(this));
}
function onFailure() private {
// allow clients to get their ether back
m_funds.changeState(FundsRegistry.State.REFUNDING);
m_funds.detachController();
}
// FIELDS
/// @notice token bonuses
FixedTimeBonuses.Data m_tokenBonuses;
/// @notice start time of the sale
uint public m_startTime;
/// @dev state of the ICO
IcoState public m_state = IcoState.INIT;
/// @dev contract responsible for token accounting
IBoomstarterToken public m_token;
/// @dev address responsile for allocation of the tokens left if ICO succeeds
address public m_tokenDistributor;
/// @dev contract responsible for investments accounting
FundsRegistry public m_funds;
/// @dev account handling investments in different currencies
address public m_nonEtherController;
/// @dev last recorded funds
uint public m_lastFundsAmount;
/// @notice minimum investment in cents
uint public constant c_MinInvestmentInCents = 500; // $5
/// @notice token price in cents
uint public constant c_tokenPriceInCents = 200; // $2
/// @notice current amount of tokens sold
uint public m_currentTokensSold;
/// @dev limit of tokens to be sold during ICO, need to leave 25% for the team
/// calculated from the current balance and the total supply
uint public c_maximumTokensSold;
} | dont mark as external! | function buy() public payable { | 1,727,601 |
./partial_match/42/0x4cd9C6D56568c6D3Aa80003a54f9267ea8FF805a/sources/ibDFD.sol | This is also used for initializing the proxy/ | function setParams(
IDFDComptroller _comptroller,
uint _redeemFactor
)
external
onlyOwner
{
require(
address(_comptroller) != address(0),
"_comptroller == 0"
);
require(
_redeemFactor <= FEE_PRECISION,
"Incorrect upper bound for fee"
);
comptroller = _comptroller;
redeemFactor = _redeemFactor;
}
| 3,313,167 |
./partial_match/1/0x089e14961f6E99b93e3972b3119a78d822B8D04a/sources/src/extensions/ERC721SeaDropRedemptionMintable.sol | Overrides the `tokenURI()` function to return baseURI + 1, 2, or 3/ | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
uint256 tokenURINumber = tokenURINumbers[tokenId];
return string(abi.encodePacked(baseURI, _toString(tokenURINumber)));
}
| 4,364,935 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
import "./MultiSig.sol";
import "./LoanContract.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
contract LoanRequest {
struct LoanStatus {
uint256 safeId;
address collateral;
uint256 tokenId;
uint256 initialLoanValue;
uint256 rate;
uint64 duration;
address lender;
address loanContract;
}
uint8 private lenderPosition = 1;
address[] public borrowers;
mapping(address => LoanStatus[]) public loanRequests;
MultiSig public multiSig;
event SubmittedLoanRequest(
address indexed _borrower,
uint256 indexed _loanId,
address collateral,
uint256 tokenId,
uint256 initialLoanValue,
uint256 rate,
uint64 duration
);
event LoanRequestChanged(
address indexed _borrower,
uint256 indexed _loanId,
string _param,
uint256 _value
);
event LoanRequestLenderChanged(
address indexed _borrower,
uint256 indexed _loanId,
address _lender
);
event DeployedLoanContract(
address indexed _contract,
address indexed _borrower,
address indexed _lender,
uint256 loanId
);
//LoanRequestEvents ctEvents;
constructor() {
multiSig = new MultiSig(2);
}
function createLoanRequest(
address _collateral,
uint256 _tokenId,
uint256 _initialLoanValue,
uint256 _rate,
uint64 _duration
) public returns (uint256) {
require(_collateral != address(0), "Collateral cannot be address 0.");
uint256 _safeId = multiSig.getSafesLength();
uint256 _loanId = loanRequests[msg.sender].length;
multiSig._createSafe(msg.sender);
// Append to borrower
if (_loanId == 0) borrowers.push(msg.sender);
// Set loan request parameters
loanRequests[msg.sender].push();
LoanStatus storage _loanRequest = loanRequests[msg.sender][_loanId];
_loanRequest.safeId = _safeId;
_loanRequest.collateral = _collateral;
_loanRequest.tokenId = _tokenId;
_loanRequest.initialLoanValue = _initialLoanValue;
_loanRequest.rate = _rate;
_loanRequest.duration = _duration;
IERC721(_collateral).safeTransferFrom(
msg.sender,
address(this),
_tokenId
);
emit SubmittedLoanRequest(
msg.sender,
_loanId,
_collateral,
_tokenId,
_initialLoanValue,
_rate,
_duration
);
return _loanId;
}
function withdrawNFT(uint256 _loanId) external {
onlyHasLoan(msg.sender);
onlyNotConfirmed(msg.sender, _loanId);
address collateral = loanRequests[msg.sender][_loanId].collateral;
uint256 tokenId = loanRequests[msg.sender][_loanId].tokenId;
IERC721(collateral).safeTransferFrom(
address(this),
msg.sender,
tokenId
);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
function isReady(address _borrower, uint256 _loanId)
public
view
returns (bool _isReady)
{
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
_isReady =
multiSig._getSignStatus(_loanRequest.safeId, _borrower) &&
multiSig._getSignStatus(
_loanRequest.safeId,
multiSig.getSigner(_loanRequest.safeId, lenderPosition)
) &&
_loanRequest.collateral != address(0) &&
_loanRequest.initialLoanValue != 0 &&
_loanRequest.duration != 0;
}
function getSignStatus(
address _signer,
address _borrower,
uint256 _loanId
) external view returns (bool) {
console.log(loanRequests[_borrower][_loanId].safeId,_signer);
return
multiSig._getSignStatus(
loanRequests[_borrower][_loanId].safeId,
_signer
);
}
function setLoanParam(
uint256 _loanId,
string memory _param,
uint256 _value
) external {
onlyHasLoan(msg.sender);
onlyNotConfirmed(msg.sender, _loanId);
LoanStatus storage _loanRequest = loanRequests[msg.sender][_loanId];
uint256 _safeId = loanRequests[msg.sender][_loanId].safeId;
address _lender = multiSig.getSafesSigner(
_loanRequest.safeId,
lenderPosition
);
if (_lender != address(0)) {
// Remove lender signature
multiSig._removeSignature(_loanRequest.safeId, _lender);
// Return funds to lender
payable(_lender).transfer(_loanRequest.initialLoanValue);
}
bytes32 _paramHash = keccak256(bytes(_param));
if (_paramHash == keccak256(bytes("value"))) {
_loanRequest.initialLoanValue = _value;
} else if (_paramHash == keccak256(bytes("rate"))) {
_loanRequest.rate = _value;
} else if (_paramHash == keccak256(bytes("duration"))) {
_loanRequest.duration = uint64(_value);
} else {
revert("Param must be one of ['value', 'rate', 'duration'].");
}
emit LoanRequestChanged(msg.sender, _loanId, _param, _value);
}
/*
* Set the loan Lender.
*
* Borrower sets the loan's lender and rates. The borrower will
* automatically sign off.
*/
function setLender(address _borrower, uint256 _loanId) external payable {
onlyHasLoan(_borrower);
onlyNotConfirmed(_borrower, _loanId);
uint256 _safeId = loanRequests[_borrower][_loanId].safeId;
if (msg.sender != multiSig.getSafesSigner(_safeId, 0)) {
/*
* If msg.sender != borrower, set msg.sender to lender and
* sign off lender.
*/
// Set lender
multiSig._setSigner(_safeId, msg.sender, lenderPosition);
// Sign off lender
sign(_borrower, _loanId);
emit LoanRequestLenderChanged(_borrower, _loanId, msg.sender);
} else {
/*
* If msg.sender == borrower, unsign lender and set lender
* to address(0).
*/
// Remove lender signature
multiSig._removeSignature(
_safeId,
multiSig.getSafesSigner(_safeId, lenderPosition)
);
// Return funds to lender
payable(multiSig.getSafesSigner(_safeId, lenderPosition)).transfer(
loanRequests[_borrower][_loanId].initialLoanValue
);
// Remove lender
multiSig._setSigner(_safeId, address(0), lenderPosition);
emit LoanRequestLenderChanged(msg.sender, _loanId, address(0));
}
loanRequests[_borrower][_loanId].lender = multiSig.getSafesSigner(
_safeId,
lenderPosition
);
}
function sign(address _borrower, uint256 _loanId) public payable {
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
require(
multiSig._getSignStatus(_loanRequest.safeId, msg.sender) == false,
"Only unsigned contracts can be accessed."
);
multiSig._sign(_loanRequest.safeId, msg.sender);
// Conditionally create contract
if (msg.sender != _borrower) {
require(
_loanRequest.initialLoanValue == msg.value,
"loan value doesn't match amount sent"
);
payable(address(this)).transfer(msg.value);
}
if (isReady(_borrower, _loanId)) {
__deployLoanContract(_borrower, _loanId);
payable(_loanRequest.loanContract).transfer(
_loanRequest.initialLoanValue
);
}
}
function removeSignature(address _borrower, uint256 _loanId) external {
onlyHasLoan(_borrower);
onlyNotConfirmed(_borrower, _loanId);
multiSig._removeSignature(
loanRequests[_borrower][_loanId].safeId,
msg.sender
);
}
function __deployLoanContract(address _borrower, uint256 _loanId) private {
onlyHasLoan(_borrower);
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
address _lender = multiSig.getSigner(
_loanRequest.safeId,
lenderPosition
);
multiSig._setConfirmedStatus(_loanRequest.safeId);
LoanContract _loanContract = new LoanContract(
[_borrower, _lender],
_loanRequest.collateral,
_loanRequest.tokenId,
_loanRequest.initialLoanValue,
_loanRequest.rate,
_loanRequest.duration
);
address _loanContractAddress = address(_loanContract);
IERC721(_loanRequest.collateral).approve(
_loanContractAddress,
_loanRequest.tokenId
);
IERC721(_loanRequest.collateral).safeTransferFrom(
address(this),
_loanContractAddress,
_loanRequest.tokenId
);
_loanRequest.loanContract = _loanContractAddress;
emit DeployedLoanContract(
_loanContractAddress,
_borrower,
_lender,
_loanId
);
}
function onlyHasLoan(address _borrower) private view {
require(
loanRequests[_borrower].length > 0,
"No loans exist for this borrower."
);
}
function onlyNotConfirmed(address _borrower, uint256 _loanId) private view {
require(
loanRequests[_borrower][_loanId].loanContract == address(0),
"Only unconfirmed contracts can be accessed."
);
}
receive() external payable {}
}
| Remove lender signature Return funds to lender | function setLoanParam(
uint256 _loanId,
string memory _param,
uint256 _value
) external {
onlyHasLoan(msg.sender);
onlyNotConfirmed(msg.sender, _loanId);
LoanStatus storage _loanRequest = loanRequests[msg.sender][_loanId];
uint256 _safeId = loanRequests[msg.sender][_loanId].safeId;
address _lender = multiSig.getSafesSigner(
_loanRequest.safeId,
lenderPosition
);
if (_lender != address(0)) {
multiSig._removeSignature(_loanRequest.safeId, _lender);
payable(_lender).transfer(_loanRequest.initialLoanValue);
}
bytes32 _paramHash = keccak256(bytes(_param));
if (_paramHash == keccak256(bytes("value"))) {
_loanRequest.initialLoanValue = _value;
_loanRequest.rate = _value;
_loanRequest.duration = uint64(_value);
revert("Param must be one of ['value', 'rate', 'duration'].");
}
emit LoanRequestChanged(msg.sender, _loanId, _param, _value);
}
| 13,103,803 |
/**
* ██╗░░██╗░█████╗░██████╗░██╗░░░░░░██████╗░░█████╗░██╗░░░░░░█████╗░██╗░░██╗██╗░░░██╗
* ██║░░██║██╔══██╗██╔══██╗██║░░░░░██╔════╝░██╔══██╗██║░░░░░██╔══██╗╚██╗██╔╝╚██╗░██╔╝
* ███████║██║░░██║██║░░██║██║░░░░░██║░░██╗░███████║██║░░░░░███████║░╚███╔╝░░╚████╔╝░
* ██╔══██║██║░░██║██║░░██║██║░░░░░██║░░╚██╗██╔══██║██║░░░░░██╔══██║░██╔██╗░░░╚██╔╝░░
* ██║░░██║╚█████╔╝██████╔╝███████╗╚██████╔╝██║░░██║███████╗██║░░██║██╔╝╚██╗░░░██║░░░
* ╚═╝░░╚═╝░╚════╝░╚═════╝░╚══════╝░╚═════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░
*
* HodlGalaxy is a coming fairlaunch ESC Token, with the best suited Tokenomics for the current ESC era, rewarding 7% in $WETH.
* HodlGalaxy's use-case is to become a 3rd party liquidity platform which allows holders of $HGALAXY to create their own liquidity/farming pools for their own token.
* We also feature a professional Doxxed Team! HodlGalaxy is here to stay and we invite you to join us.
*
* During the FairLaunch of HodlGalaxy a max buy of 1.5 ETH will be set for the first 1 minute to stop long holders being able to dump large amounts of tokens.
* The contract address will be released for everyone at the same time to stop bots from ruining the launch.
*
* Token Tax Breakdown: 7% $WETH Rewards, 4% Marketing Fee, 2% Liquidity.
*
* Website https://HodlGalaxy.com
* Telegram https://t.me/HodlGalaxy
*/
// SPDX-License-Identifier: MIT
// File: contracts/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: contracts/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/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/Address.sol
pragma solidity ^0.6.2;
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/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/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*/
contract ERC20 is Context, IERC20, Ownable {
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;
bool public inCooldown = false;
uint256 public maxTxAmount = 1000000000000000 * 1000000000000000000;
mapping (address => bool) private _isExcluded;
mapping (address => uint256) private _tranzCount;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public { //, uint256 totalSupply
_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");
if ((inCooldown == true) && !(_isExcluded[sender] || _isExcluded[recipient])) {
require(_tranzCount[sender] == 0, "inCooldown: only one tranzaction allowed");
require(amount < maxTxAmount, "inCooldown: Transfer amount exceeds the maxTxAmount");
_tranzCount[sender]++;
}
_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 _add(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: add 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 { }
function setInCooldown(bool _inCooldown) public onlyOwner {
inCooldown = _inCooldown;
}
function setMaxTxAmount(uint256 _maxTxAmount) public onlyOwner {
maxTxAmount = _maxTxAmount;
}
function isExcluded(address account) public view returns(bool) {
return _isExcluded[account];
}
function setIsExcluded(address account) public onlyOwner {
_isExcluded[account] = true;
}
function tranzCount(address account) public view returns(uint256) {
return _tranzCount[account];
}
}
// File: contracts/MyToken.sol
pragma solidity >=0.6.12;
contract HodlGalaxy is Context, ERC20 {
using SafeMath for uint256;
using Address for address;
event Burn(address indexed _sender, uint256 amount);
event Add(address indexed account, uint256 amount);
uint tokenTotalSupply = 100000000;
constructor() public ERC20("HodlGalaxy", "HGALAXY") {
_add(msg.sender, tokenTotalSupply * (10 ** uint256(decimals())));
}
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
emit Burn(_msgSender(), amount);
}
function add(address account, uint256 amount) public onlyOwner {
_add(account, amount);
emit Add(account, amount);
}
} | See {IERC20-totalSupply}./ | function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
| 8,304 |
/**
*Submitted for verification at Etherscan.io on 2022-02-27
*/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (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() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @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);
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* 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) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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 _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
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;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_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 ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_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 = uint64(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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), 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[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn 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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @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 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
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 TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* 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`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
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.
* And also called after one token has been burned.
*
* 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` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/mofos.sol
pragma solidity ^0.8.7;
contract MofosNft is ERC721A, Ownable {
using Strings for uint256;
address breedingContract;
string public baseApiURI;
bytes32 private whitelistRoot;
//General Settings
uint16 public maxMintAmountPerTransaction = 10;
uint16 public maxMintAmountPerWallet = 10;
//whitelisting Settings
uint16 public maxMintAmountPerWhitelist = 10;
//Inventory
uint256 public maxSupply = 10011;
//Prices
uint256 public cost = 0.052 ether;
uint256 public whitelistCost = 0.042 ether;
//Utility
bool public paused = false;
bool public whiteListingSale = true;
//mapping
mapping(address => uint256) private whitelistedMints;
constructor(string memory _baseUrl) ERC721A("MofosNFT", "MOFO") {
baseApiURI = _baseUrl;
}
//This function will be used to extend the project with more capabilities
function setBreedingContractAddress(address _bAddress) public onlyOwner {
breedingContract = _bAddress;
}
//this function can be called only from the extending contract
function mintExternal(address _address, uint256 _mintAmount) external {
require(
msg.sender == breedingContract,
"Sorry you dont have permission to mint"
);
_safeMint(_address, _mintAmount);
}
function setWhitelistingRoot(bytes32 _root) public onlyOwner {
whitelistRoot = _root;
}
// Verify that a given leaf is in the tree.
function _verify(
bytes32 _leafNode,
bytes32[] memory proof
) internal view returns (bool) {
return MerkleProof.verify(proof, whitelistRoot, _leafNode);
}
// Generate the leaf node (just the hash of tokenID concatenated with the account address)
function _leaf(address account) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account));
}
//whitelist mint
function mintWhitelist(
bytes32[] calldata proof,
uint256 _mintAmount
) public payable {
//Normal WL Verifications
require(
_verify(_leaf(msg.sender), proof),
"Invalid proof"
);
require(
(whitelistedMints[msg.sender] + _mintAmount) <=
maxMintAmountPerWhitelist,
"Exceeds Max Mint amount"
);
require(
msg.value >= (whitelistCost * _mintAmount),
"Insuffient funds"
);
//END WL Verifications
//Mint
_mintLoop(msg.sender, _mintAmount);
whitelistedMints[msg.sender] =
whitelistedMints[msg.sender] +
_mintAmount;
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
// public
function mint(uint256 _mintAmount) public payable {
if (msg.sender != owner()) {
uint256 ownerTokenCount = balanceOf(msg.sender);
require(!paused);
require(!whiteListingSale, "You cant mint on Presale");
require(_mintAmount > 0, "Mint amount should be greater than 0");
require(
_mintAmount <= maxMintAmountPerTransaction,
"Sorry you cant mint this amount at once"
);
require(
totalSupply() + _mintAmount <= maxSupply,
"Exceeds Max Supply"
);
require(
(ownerTokenCount + _mintAmount) <= maxMintAmountPerWallet,
"Sorry you cant mint more"
);
require(msg.value >= cost * _mintAmount, "Insuffient funds");
}
_mintLoop(msg.sender, _mintAmount);
}
function gift(address _to, uint256 _mintAmount) public onlyOwner {
_mintLoop(_to, _mintAmount);
}
function airdrop(address[] memory _airdropAddresses) public onlyOwner {
for (uint256 i = 0; i < _airdropAddresses.length; i++) {
address to = _airdropAddresses[i];
_mintLoop(to, 1);
}
}
function _baseURI() internal view virtual override returns (string memory) {
return baseApiURI;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString()))
: "";
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setWhitelistingCost(uint256 _newCost) public onlyOwner {
whitelistCost = _newCost;
}
function setmaxMintAmountPerTransaction(uint16 _amount) public onlyOwner {
maxMintAmountPerTransaction = _amount;
}
function setMaxMintAmountPerWallet(uint16 _amount) public onlyOwner {
maxMintAmountPerWallet = _amount;
}
function setMaxMintAmountPerWhitelist(uint16 _amount) public onlyOwner {
maxMintAmountPerWhitelist = _amount;
}
function setMaxSupply(uint256 _supply) public onlyOwner {
maxSupply = _supply;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseApiURI = _newBaseURI;
}
function togglePause() public onlyOwner {
paused = !paused;
}
function toggleWhiteSale() public onlyOwner {
whiteListingSale = !whiteListingSale;
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
_safeMint(_receiver, _mintAmount);
}
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
function withdraw() public payable onlyOwner {
uint256 balance = address(this).balance;
uint256 share1 = (balance * 9) / 200;
uint256 share2 = (balance * 20) / 200;
(bool shareholder3, ) = payable(
0x16c7Fbd3D3f4d212624ba005D25B4e7Bcd1A65c7
).call{value: share1}("");
require(shareholder3);
(bool shareholder2, ) = payable(
0xf226E4A2779a0a2850dCBAE91130Fd285a6343Bc
).call{value: share2}("");
require(shareholder2);
(bool os, ) = payable(0x097EAA98fF7386164CCB612D7DE5DdBF5651EA17).call{value: address(this).balance}("");
require(os);
}
} | whitelist mintNormal WL VerificationsEND WL VerificationsMint | function mintWhitelist(
bytes32[] calldata proof,
uint256 _mintAmount
) public payable {
require(
_verify(_leaf(msg.sender), proof),
"Invalid proof"
);
require(
(whitelistedMints[msg.sender] + _mintAmount) <=
maxMintAmountPerWhitelist,
"Exceeds Max Mint amount"
);
require(
msg.value >= (whitelistCost * _mintAmount),
"Insuffient funds"
);
_mintLoop(msg.sender, _mintAmount);
whitelistedMints[msg.sender] =
whitelistedMints[msg.sender] +
_mintAmount;
}
| 2,390,792 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IPinataPrizePool.sol";
import "../interfaces/IPinataStrategy.sol";
import "../interfaces/IPinataVault.sol";
/**
* @dev Implementation of a manager for each pool of Pinata Finance protocol.
* This is the contract that using to managing state, permission.
* and also managing contract in which is part of each pool.
*/
contract PinataManager {
using SafeMath for uint256;
enum LOTTERY_STATE {
OPEN,
CLOSED,
CALCULATING_WINNER,
WINNERS_PENDING,
READY
}
/* ========================== Variables ========================== */
address public manager; // The current manager.
address public pendingManager; // The address pending to become the manager once accepted.
address public timeKeeper; // keeper of pool state.
uint256 public openTime;
uint256 public closingTime;
uint256 public drawingTime;
bool public allowCloseAnytime;
bool public allowDrawAnytime;
LOTTERY_STATE public lotteryState;
// Contracts
address public vault;
address public strategy;
address public prizePool;
address public randomNumberGenerator;
// Fee Receiver
address public strategist; // Address of the strategy author/deployer where strategist fee will go.
address public pinataFeeRecipient; // Address where to send pinata's fees (fund of platform).
/* ========================== Events ========================== */
/**
* @dev Emitted when Pool is open ready to deposit.
*/
event PoolOpen();
/**
* @dev Emitted when Pool is closed deposit will not be allowed.
*/
event PoolClosed();
/**
* @dev Emitted when Pool is calculating for lucky winners.
*/
event PoolCalculatingWinners();
/**
* @dev Emitted when Pool is getting numbers from Chainlink and waiting for reward distribution.
*/
event PoolWinnersPending();
/**
* @dev Emitted when Pool is ready to be open.
*/
event PoolReady();
/**
* @dev Emitted when address of vault is setted.
*/
event VaultSetted(address vault);
/**
* @dev Emitted when address of strategy is setted.
*/
event StrategySetted(address strategy);
/**
* @dev Emitted when address of prize pool is setted.
*/
event PrizePoolSetted(address prizePool);
/**
* @dev Emitted when address of random number generator is setted.
*/
event RandomNumberGeneratorSetted(address randomNumberGenerator);
/**
* @dev Emitted when address of strategist (dev) is setted.
*/
event StrategistSetted(address strategist);
/**
* @dev Emitted when address of pinataFeeRecipient (treasury) is setted.
*/
event PinataFeeRecipientSetted(address pinataFeeRecipient);
/**
* @dev Emitted when manager is setted.
*/
event ManagerSetted(address manager);
/**
* @dev Emitted when pending manager is setted.
*/
event PendingManagerSetted(address pendingManager);
/**
* @dev Emitted when time keeper is setted.
*/
event TimeKeeperSetted(address timeKeeper);
/**
* @dev Emitted when changing allowCloseAnytime or allowDrawAnytime.
*/
event PoolTimerSetted(bool allowCloseAnytime, bool allowDrawAnytime);
/**
/* ========================== Modifier ========================== */
/**
* @dev Modifier to make a function callable only when called by time keeper.
*
* Requirements:
*
* - The caller have to be setted as time keeper.
*/
modifier onlyTimeKeeper() {
require(
msg.sender == timeKeeper,
"PinataManager: Only Timekeeper allowed!"
);
_;
}
/**
* @dev Modifier to make a function callable only when called by manager.
*
* Requirements:
*
* - The caller have to be setted as manager.
*/
modifier onlyManager() {
require(msg.sender == manager, "PinataManager: Only Manager allowed!");
_;
}
/* ========================== Functions ========================== */
/**
* @dev Setting up contract's state, permission is setted to deployer as default.
* @param _allowCloseAnytime boolean in which is pool allowed to be closed any time.
* @param _allowDrawAnytime boolean in which is pool allowed to be able to draw rewards any time.
*/
constructor(bool _allowCloseAnytime, bool _allowDrawAnytime) public {
allowCloseAnytime = _allowCloseAnytime;
allowDrawAnytime = _allowDrawAnytime;
lotteryState = LOTTERY_STATE.READY;
manager = msg.sender;
pendingManager = address(0);
vault = address(0);
timeKeeper = msg.sender;
}
/**
* @dev Start new lottery round set lottery state to open. only allow when lottery is in ready state.
* only allow by address setted as time keeper.
* @param _closingTime timestamp of desired closing time.
* @param _drawingTime timestamp of desired drawing time.
*/
function startNewLottery(uint256 _closingTime, uint256 _drawingTime)
public
onlyTimeKeeper
{
require(
lotteryState == LOTTERY_STATE.READY,
"PinataManager: can't start a new lottery yet!"
);
drawingTime = _drawingTime;
openTime = block.timestamp;
closingTime = _closingTime;
lotteryState = LOTTERY_STATE.OPEN;
emit PoolOpen();
}
/**
* @dev Closing ongoing lottery set status of pool to closed.
* only allow by address setted as time keeper.
*/
function closePool() public onlyTimeKeeper {
if (!allowCloseAnytime) {
require(
block.timestamp >= closingTime,
"PinataManager: cannot be closed before closing time!"
);
}
lotteryState = LOTTERY_STATE.CLOSED;
emit PoolClosed();
}
/**
* @dev Picking winners for this round calling harvest on strategy to ensure reward is updated.
* calling drawing number on prize pool to calculating for lucky winners.
* only allow by address setted as time keeper.
*/
function calculateWinners() public onlyTimeKeeper {
if (!allowDrawAnytime) {
require(
block.timestamp >= drawingTime,
"PinataManager: cannot be calculate winners before drawing time!"
);
}
IPinataStrategy(strategy).harvest();
IPinataPrizePool(prizePool).drawNumber();
lotteryState = LOTTERY_STATE.CALCULATING_WINNER;
emit PoolCalculatingWinners();
}
/**
* @dev Called when winners is calculated only allow to be called from prize pool.
* setting the lottery state winners pending since reward need to be distributed.
* @dev process have to be seperated since Chainlink VRF only allow 200k for gas limit.
*/
function winnersCalculated() external {
require(
msg.sender == prizePool,
"PinataManager: Caller need to be PrizePool"
);
lotteryState = LOTTERY_STATE.WINNERS_PENDING;
emit PoolWinnersPending();
}
/**
* @dev Called when winners is calculated only allow to be called from prize pool.
* setting the lottery state to ready for next round.
*/
function rewardDistributed() external {
require(
msg.sender == prizePool,
"PinataManager: Caller need to be PrizePool"
);
lotteryState = LOTTERY_STATE.READY;
emit PoolReady();
}
/* ========================== Getter Functions ========================== */
/**
* @dev getting current state of the pool.
*/
function getState() public view returns (LOTTERY_STATE) {
return lotteryState;
}
/**
* @dev getting timeline of current round setted when new lottery started.
*/
function getTimeline()
external
view
returns (
uint256,
uint256,
uint256
)
{
return (openTime, closingTime, drawingTime);
}
/**
* @dev get address of vault setted.
*/
function getVault() external view returns (address) {
return vault;
}
/**
* @dev get address of strategy setted.
*/
function getStrategy() external view returns (address) {
return strategy;
}
/**
* @dev get address of prize pool setted.
*/
function getPrizePool() external view returns (address) {
return prizePool;
}
/**
* @dev get address of random number generator setted.
*/
function getRandomNumberGenerator() external view returns (address) {
return randomNumberGenerator;
}
/**
* @dev get address of strategist (dev) setted.
*/
function getStrategist() external view returns (address) {
return strategist;
}
/**
* @dev get address of pinata fee recipient (treasury) setted.
*/
function getPinataFeeRecipient() external view returns (address) {
return pinataFeeRecipient;
}
/**
* @dev get manager status of address provided.
* @param _manager is address want to know status of.
*/
function getIsManager(address _manager) external view returns (bool) {
return _manager == manager;
}
/**
* @dev get timekeeper status of address provided.
* @param _timeKeeper is address want to know status of.
*/
function getIsTimekeeper(address _timeKeeper) external view returns (bool) {
return _timeKeeper == timeKeeper;
}
/* ========================== Admin Setter Functions ========================== */
/**
* @dev setting address of vault.
* @param _vault is address of vault.
*/
function setVault(address _vault) external onlyManager {
require(vault == address(0), "PinataManager: Vault already set!");
vault = _vault;
emit VaultSetted(vault);
}
/**
* @dev setting address of strategy. perform retireStrat operation to withdraw the fund from
* old strategy to new strategy.
* @param _strategy is address of strategy.
*/
function setStrategy(address _strategy) external onlyManager {
if (strategy != address(0)) {
IPinataStrategy(strategy).retireStrat();
}
strategy = _strategy;
IPinataVault(vault).earn();
emit StrategySetted(strategy);
}
/**
* @dev setting address of prize pool. perform retirePrizePool operation to withdraw the fund from
* old prizePool to vault. but the allocated reward is remain in the old prize pool.
* participant will have to withdraw and deposit again to participate in new prize pool.
* @param _prizePool is address of new prize pool.
*/
function setPrizePool(address _prizePool) external onlyManager {
require(
lotteryState == LOTTERY_STATE.READY,
"PinataManager: only allow to set prize pool in ready state!"
);
if (prizePool != address(0)) {
IPinataPrizePool(prizePool).retirePrizePool();
}
prizePool = _prizePool;
emit PrizePoolSetted(prizePool);
}
/**
* @dev setting address of random number generator.
* @param _randomNumberGenerator is address of random number generator.
*/
function setRandomNumberGenerator(address _randomNumberGenerator)
external
onlyManager
{
randomNumberGenerator = _randomNumberGenerator;
emit RandomNumberGeneratorSetted(randomNumberGenerator);
}
/**
* @dev setting address of strategist.
* @param _strategist is address of strategist.
*/
function setStrategist(address _strategist) external onlyManager {
strategist = _strategist;
emit StrategistSetted(strategist);
}
/**
* @dev setting address of pinataFeeRecipient.
* @param _pinataFeeRecipient is address of pinataFeeRecipient.
*/
function setPinataFeeRecipient(address _pinataFeeRecipient)
external
onlyManager
{
pinataFeeRecipient = _pinataFeeRecipient;
emit PinataFeeRecipientSetted(pinataFeeRecipient);
}
/**
* @dev Set the pending manager, which will be the manager once accepted.
* @param _pendingManager The address to become the pending governor.
*/
function setPendingManager(address _pendingManager) external onlyManager {
pendingManager = _pendingManager;
emit PendingManagerSetted(_pendingManager);
}
/**
* @dev Set the pending manager, which will be the manager once accepted.
* @param _accept is to accept role as manager or not.
*/
function acceptManager(bool _accept) external {
require(
msg.sender == pendingManager,
"PinataManager: not the pending manager"
);
pendingManager = address(0);
if (_accept) {
manager = msg.sender;
emit ManagerSetted(msg.sender);
}
}
/**
* @dev setting status of time keeper.
* @param _timeKeeper is address wish to changing status.
*/
function setTimeKeeper(address _timeKeeper) external onlyManager {
timeKeeper = _timeKeeper;
emit TimeKeeperSetted(_timeKeeper);
}
/**
* @dev setting pool to beable to close or draw anytime or only when past time setted.
* @param _allowCloseAnytime is address wish to changing status.
* @param _allowDrawAnytime is address wish to changing status.
*/
function setPoolAllow(bool _allowCloseAnytime, bool _allowDrawAnytime) external onlyManager {
allowCloseAnytime = _allowCloseAnytime;
allowDrawAnytime = _allowDrawAnytime;
emit PoolTimerSetted(allowCloseAnytime, allowDrawAnytime);
}
/**
* @dev use for emergency in case state got stuck.
* state of the pool should progress automatically.
* this function is provided just in case.
*/
function setStateToReady() external onlyManager {
lotteryState = LOTTERY_STATE.READY;
emit PoolReady();
}
}
| get timekeeper status of address provided. _timeKeeper is address want to know status of./ | function getIsTimekeeper(address _timeKeeper) external view returns (bool) {
return _timeKeeper == timeKeeper;
}
| 991,949 |
/**
Fuck these SCAMS, Fuck these TAX coins and most importantly FUCK THESE HOES. It's time to make a real fking coin to celebrate Saint Patricks Day!
0 Tax or Dev fee, only 2% of buys/sells go back to the liquidity pool, aka HODLERS!
- 2% TX limit.
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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);
}
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);
}
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);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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 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 IUniswapV2Router02 {
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 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;
}
contract STPatricksApe 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("St Patricks Ape", "STAPE") {
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 = 0;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 20_000_000 * 1e18; // 2% from total supply maxTransactionAmount
maxWallet = 1_000_000_000 * 1e18; // No limits APES
swapTokensAtAmount = (totalSupply * 5) / 1000000; // 5% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xe79c4Ba3b1482108b05dcbeB5ecc54d420957AAb); // set as marketing wallet
devWallet = address(0xe79c4Ba3b1482108b05dcbeB5ecc54d420957AAb); // 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 <= 90, "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("St Patricks Ape", "STAPE") {
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 = 0;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 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);
| 14,726,938 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
library SafeMath {
function ADD802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function ADD802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function SUB29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB29(a, b, "SafeMath: subtraction underflow");
}
function SUB29(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 MUL631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function MUL631(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function DIV549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV549(a, b, "SafeMath: division by zero");
}
function DIV549(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD667(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD667(a, b, "SafeMath: modulo by zero");
}
function MOD667(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface IKeep2r {
function ADDVOTES925(address voter, uint amount) external; //inject NONSTANDARD NAMING
function REMOVEVOTES795(address voter, uint amount) external; //inject NONSTANDARD NAMING
function ADDKPRCREDIT324(address job, uint amount) external; //inject NONSTANDARD NAMING
function APPROVELIQUIDITY19(address liquidity) external; //inject NONSTANDARD NAMING
function REVOKELIQUIDITY95(address liquidity) external; //inject NONSTANDARD NAMING
function ADDJOB704(address job) external; //inject NONSTANDARD NAMING
function REMOVEJOB261(address job) external; //inject NONSTANDARD NAMING
function SETKEEP2RHELPER717(address _kprh) external; //inject NONSTANDARD NAMING
function SETGOVERNANCE887(address _governance) external; //inject NONSTANDARD NAMING
function ACCEPTGOVERNANCE419() external; //inject NONSTANDARD NAMING
function DISPUTE17(address keeper) external; //inject NONSTANDARD NAMING
function SLASH754(address bonded, address keeper, uint amount) external; //inject NONSTANDARD NAMING
function REVOKE96(address keeper) external; //inject NONSTANDARD NAMING
function RESOLVE192(address keeper) external; //inject NONSTANDARD NAMING
function GETPRIORVOTES700(address account, uint blockNumber) external view returns (uint); //inject NONSTANDARD NAMING
function TOTALBONDED836() external view returns (uint); //inject NONSTANDARD NAMING
}
contract Governance {
using SafeMath for uint;
string public constant name820 = "Governance"; //inject NONSTANDARD NAMING
uint public _quorumVotes = 5000; // % of total supply required
uint public _proposalThreshold = 5000;
uint public constant base706 = 10000; //inject NONSTANDARD NAMING
function SETQUORUM684(uint quorum_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Governance::setQuorum: timelock only");
require(quorum_ <= base706, "Governance::setQuorum: quorum_ > BASE");
_quorumVotes = quorum_;
}
function QUORUMVOTES610() public view returns (uint) { //inject NONSTANDARD NAMING
return KPR.TOTALBONDED836().MUL631(_quorumVotes).DIV549(base706);
}
function PROPOSALTHRESHOLD741() public view returns (uint) { //inject NONSTANDARD NAMING
return KPR.TOTALBONDED836().MUL631(_proposalThreshold).DIV549(base706);
}
function SETTHRESHOLD755(uint threshold_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Governance::setQuorum: timelock only");
require(threshold_ <= base706, "Governance::setThreshold: threshold_ > BASE");
_proposalThreshold = threshold_;
}
function PROPOSALMAXOPERATIONS305() public pure returns (uint) { return 10; } // 10 actions //inject NONSTANDARD NAMING
function VOTINGDELAY891() public pure returns (uint) { return 1; } // 1 block //inject NONSTANDARD NAMING
function VOTINGPERIOD297() public pure returns (uint) { return 40_320; } // ~7 days in blocks (assuming 15s blocks) //inject NONSTANDARD NAMING
IKeep2r immutable public KPR;
uint public proposalCount;
struct Proposal {
uint id;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
mapping (address => Receipt) receipts;
}
struct Receipt {
bool hasVoted;
bool support;
uint votes;
}
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
mapping (uint => Proposal) public proposals;
mapping (address => uint) public latestProposalIds;
bytes32 public constant domain_typehash397 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING
bytes32 public immutable DOMAINSEPARATOR;
bytes32 public constant ballot_typehash182 = keccak256("Ballot(uint256 proposalId,bool support)"); //inject NONSTANDARD NAMING
event PROPOSALCREATED434(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); //inject NONSTANDARD NAMING
event VOTECAST909(address voter, uint proposalId, bool support, uint votes); //inject NONSTANDARD NAMING
event PROPOSALCANCELED450(uint id); //inject NONSTANDARD NAMING
event PROPOSALQUEUED490(uint id, uint eta); //inject NONSTANDARD NAMING
event PROPOSALEXECUTED781(uint id); //inject NONSTANDARD NAMING
function PROPOSEJOB470(address job) public { //inject NONSTANDARD NAMING
require(msg.sender == address(KPR), "Governance::proposeJob: only VOTER can propose new jobs");
address[] memory targets;
targets[0] = address(KPR);
string[] memory signatures;
signatures[0] = "addJob(address)";
bytes[] memory calldatas;
calldatas[0] = abi.encode(job);
uint[] memory values;
values[0] = 0;
_PROPOSE700(targets, values, signatures, calldatas, string(abi.encodePacked("Governance::proposeJob(): ", job)));
}
function PROPOSE926(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { //inject NONSTANDARD NAMING
require(KPR.GETPRIORVOTES700(msg.sender, block.number.SUB29(1)) >= PROPOSALTHRESHOLD741(), "Governance::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Governance::propose: proposal function information arity mismatch");
require(targets.length != 0, "Governance::propose: must provide actions");
require(targets.length <= PROPOSALMAXOPERATIONS305(), "Governance::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = STATE767(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "Governance::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "Governance::propose: one live proposal per proposer, found an already pending proposal");
}
return _PROPOSE700(targets, values, signatures, calldatas, description);
}
function _PROPOSE700(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) internal returns (uint) { //inject NONSTANDARD NAMING
uint startBlock = block.number.ADD802(VOTINGDELAY891());
uint endBlock = startBlock.ADD802(VOTINGPERIOD297());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit PROPOSALCREATED434(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function QUEUE934(uint proposalId) public { //inject NONSTANDARD NAMING
require(STATE767(proposalId) == ProposalState.Succeeded, "Governance::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = block.timestamp.ADD802(delay);
for (uint i = 0; i < proposal.targets.length; i++) {
_QUEUEORREVERT932(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit PROPOSALQUEUED490(proposalId, eta);
}
function _QUEUEORREVERT932(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING
require(!queuedTransactions[keccak256(abi.encode(target, value, signature, data, eta))], "Governance::_queueOrRevert: proposal action already queued at eta");
_QUEUETRANSACTION380(target, value, signature, data, eta);
}
function EXECUTE292(uint proposalId) public payable { //inject NONSTANDARD NAMING
require(guardian == address(0x0) || msg.sender == guardian, "Governance:execute: !guardian");
require(STATE767(proposalId) == ProposalState.Queued, "Governance::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
_EXECUTETRANSACTION42(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit PROPOSALEXECUTED781(proposalId);
}
function CANCEL285(uint proposalId) public { //inject NONSTANDARD NAMING
ProposalState state = STATE767(proposalId);
require(state != ProposalState.Executed, "Governance::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(proposal.proposer != address(KPR) &&
KPR.GETPRIORVOTES700(proposal.proposer, block.number.SUB29(1)) < PROPOSALTHRESHOLD741(), "Governance::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
_CANCELTRANSACTION608(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit PROPOSALCANCELED450(proposalId);
}
function GETACTIONS567(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { //inject NONSTANDARD NAMING
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function GETRECEIPT636(uint proposalId, address voter) public view returns (Receipt memory) { //inject NONSTANDARD NAMING
return proposals[proposalId].receipts[voter];
}
function STATE767(uint proposalId) public view returns (ProposalState) { //inject NONSTANDARD NAMING
require(proposalCount >= proposalId && proposalId > 0, "Governance::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes.ADD802(proposal.againstVotes) < QUORUMVOTES610()) {
return ProposalState.Defeated;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta.ADD802(grace_period471)) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function CASTVOTE458(uint proposalId, bool support) public { //inject NONSTANDARD NAMING
_CASTVOTE871(msg.sender, proposalId, support);
}
function CASTVOTEBYSIG199(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING
bytes32 structHash = keccak256(abi.encode(ballot_typehash182, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Governance::castVoteBySig: invalid signature");
_CASTVOTE871(signatory, proposalId, support);
}
function _CASTVOTE871(address voter, uint proposalId, bool support) internal { //inject NONSTANDARD NAMING
require(STATE767(proposalId) == ProposalState.Active, "Governance::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "Governance::_castVote: voter already voted");
uint votes = KPR.GETPRIORVOTES700(voter, proposal.startBlock);
if (support) {
proposal.forVotes = proposal.forVotes.ADD802(votes);
} else {
proposal.againstVotes = proposal.againstVotes.ADD802(votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VOTECAST909(voter, proposalId, support, votes);
}
function GETCHAINID291() internal pure returns (uint) { //inject NONSTANDARD NAMING
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
event NEWDELAY307(uint indexed newDelay); //inject NONSTANDARD NAMING
event CANCELTRANSACTION220(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
event EXECUTETRANSACTION925(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
event QUEUETRANSACTION307(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
uint public constant grace_period471 = 14 days; //inject NONSTANDARD NAMING
uint public constant minimum_delay353 = 1 days; //inject NONSTANDARD NAMING
uint public constant maximum_delay422 = 30 days; //inject NONSTANDARD NAMING
uint public delay = minimum_delay353;
address public guardian;
address public pendingGuardian;
function SETGUARDIAN20(address _guardian) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setGuardian: !guardian");
pendingGuardian = _guardian;
}
function ACCEPTGUARDIANSHIP599() external { //inject NONSTANDARD NAMING
require(msg.sender == pendingGuardian, "Keep2rGovernance::setGuardian: !pendingGuardian");
guardian = pendingGuardian;
}
function ADDVOTES925(address voter, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addVotes: !guardian");
KPR.ADDVOTES925(voter, amount);
}
function REMOVEVOTES795(address voter, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::removeVotes: !guardian");
KPR.REMOVEVOTES795(voter, amount);
}
function ADDKPRCREDIT324(address job, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addKPRCredit: !guardian");
KPR.ADDKPRCREDIT324(job, amount);
}
function APPROVELIQUIDITY19(address liquidity) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::approveLiquidity: !guardian");
KPR.APPROVELIQUIDITY19(liquidity);
}
function REVOKELIQUIDITY95(address liquidity) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::revokeLiquidity: !guardian");
KPR.REVOKELIQUIDITY95(liquidity);
}
function ADDJOB704(address job) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addJob: !guardian");
KPR.ADDJOB704(job);
}
function REMOVEJOB261(address job) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::removeJob: !guardian");
KPR.REMOVEJOB261(job);
}
function SETKEEP2RHELPER717(address kprh) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setKeep2rHelper: !guardian");
KPR.SETKEEP2RHELPER717(kprh);
}
function SETGOVERNANCE887(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setGovernance: !guardian");
KPR.SETGOVERNANCE887(_governance);
}
function ACCEPTGOVERNANCE419() external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::acceptGovernance: !guardian");
KPR.ACCEPTGOVERNANCE419();
}
function DISPUTE17(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::dispute: !guardian");
KPR.DISPUTE17(keeper);
}
function SLASH754(address bonded, address keeper, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::slash: !guardian");
KPR.SLASH754(bonded, keeper, amount);
}
function REVOKE96(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::revoke: !guardian");
KPR.REVOKE96(keeper);
}
function RESOLVE192(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::resolve: !guardian");
KPR.RESOLVE192(keeper);
}
mapping (bytes32 => bool) public queuedTransactions;
constructor(address token_) public {
guardian = msg.sender;
KPR = IKeep2r(token_);
DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash397, keccak256(bytes(name820)), GETCHAINID291(), address(this)));
}
receive() external payable { }
function SETDELAY397(uint delay_) public { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= minimum_delay353, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= maximum_delay422, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NEWDELAY307(delay);
}
function _QUEUETRANSACTION380(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes32) { //inject NONSTANDARD NAMING
require(eta >= GETBLOCKTIMESTAMP893().ADD802(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QUEUETRANSACTION307(txHash, target, value, signature, data, eta);
return txHash;
}
function _CANCELTRANSACTION608(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CANCELTRANSACTION220(txHash, target, value, signature, data, eta);
}
function _EXECUTETRANSACTION42(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes memory) { //inject NONSTANDARD NAMING
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(GETBLOCKTIMESTAMP893() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(GETBLOCKTIMESTAMP893() <= eta.ADD802(grace_period471), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value:value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit EXECUTETRANSACTION925(txHash, target, value, signature, data, eta);
return returnData;
}
function GETBLOCKTIMESTAMP893() internal view returns (uint) { //inject NONSTANDARD NAMING
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
} | inject NONSTANDARD NAMING | function SLASH754(address bonded, address keeper, uint amount) external; | 12,851,101 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
* Defines 4 roles Donor, Client, CSO, and Agent for sending around value.
* The Donor mints tokens by sending a wire transfer to the Client who holds the underlying money.
* The Donor can then give those tokens to the CSO to pay for things in the conflict zone.
* The CSOs can cash out their tokens with Agents in the conflict zone.
* Agents cash out thier tokens with the Client outside the conflict zone, at which point the Client can burn the tokens.
* TODO for all the functions that require some external flow (eg wire transfer, cash exchange) we should add some type of confirmation
* TODO investigate OpenZepplin AccessControl - at first glance it didn't match our needs but should investigate again
*/
contract HawalaCoin is ERC1155, ERC1155Receiver, ERC1155Holder, Ownable {
using Counters for Counters.Counter;
Counters.Counter _tokenCounter;
mapping(address => Role) public users;
enum Role {NONE, DONOR, CLIENT, CSO, AGENT}
Counters.Counter _missionCounter;
struct Mission {
address csoAddr;
address agentAddr;
uint256 tokenId;
uint256 amount;
bool completed;
}
mapping(uint256 => Mission) public missions;
// TODO add events
/**
* Called by the contract owner
*/
constructor() ERC1155("") {}
/**
* Bubble supportsInterface down the class hierarchy
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* TODO add rules:
* 1) DONOR can only be added by contract owner
* 2) CLIENT can only be added by DONOR
* 3) CSO can only be added by DONOR
* 4) AGENT can only be added by CLIENT
* TODO add check if user already exists - error or update?
*/
function addUser(address addr, Role role) public {
users[addr] = role;
}
/**
* Mints an amount of new tokens for the Donor which are redeamable at the Client
* TODO add rule: only Donor can call
* TODO add currency field, right now we assume amount in USD in pennies
* TODO add some type of verification/confirmation to ensure minted tokens truly reflect new bank balance
*/
function mint(address donorAddr, address clientAddr, uint256 amount) public {
require(donorAddr == msg.sender, "Sender must match the donorAddr");
uint256 tokenId = _tokenCounter.current();
_tokenCounter.increment();
_mint(donorAddr, tokenId, amount, abi.encodePacked(clientAddr));
}
/**
* TODO add rule: only Client can call
*/
function burn(address clientAddr, uint256 tokenId, uint256 amount) public {
require(clientAddr == msg.sender, "Sender must match the clientAddr");
_burn(msg.sender, tokenId, amount);
}
/**
* TODO add rule: only CSO can call
* Creates mission for a specific agent and transfers tokens to contract for escrow
*/
function createMission(address csoAddr, address agentAddr, uint256 tokenId, uint256 amount) public {
require(csoAddr == msg.sender, "Sender must match the csoAddr");
uint256 missionId = _missionCounter.current();
missions[missionId] = Mission({
csoAddr: csoAddr,
agentAddr: agentAddr,
tokenId: tokenId,
amount: amount,
completed: false
});
_missionCounter.increment();
this.safeTransferFrom(csoAddr, address(this), tokenId, amount, "");
}
/**
* TODO add rule: only Agent can call
* TODO add functionality to allow for partial mission completions which would return some amount back to CSO
*/
function completeMission(address agentAddr, uint256 missionId) public {
require(agentAddr == msg.sender, "Sender must match the agentAddr");
uint256 tokenId = missions[missionId].tokenId;
uint256 amount = missions[missionId].amount;
missions[missionId].completed = true;
this.safeTransferFrom(address(this), agentAddr, tokenId, amount, "");
}
/**
* Convinience function to get the current token id so we can loop through all previous tokens
*/
function currentTokenId() public view returns (uint256) {
return _tokenCounter.current();
}
/**
* Convinience function to get the current missions id so we can loop through all previous missions
*/
function currentMissionId() public view returns (uint256) {
return _missionCounter.current();
}
}
| TODO add rule: only Client can call/ | function burn(address clientAddr, uint256 tokenId, uint256 amount) public {
require(clientAddr == msg.sender, "Sender must match the clientAddr");
_burn(msg.sender, tokenId, amount);
}
| 15,859,737 |
./full_match/1/0xD05ca8f5B9fd7fa84D1c92b2e64feA8259EeC1ae/sources/browser/CompMiner_flat.sol | File: localhost/contracts/interfaces/ILendingPoolAddressesProvider.sol/ | interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address _pool) external;
function getLendingPoolCore() external view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) external;
function getLendingPoolDataProvider() external view returns (address);
function setLendingPoolDataProviderImpl(address _provider) external;
function getLendingPoolParametersProvider() external view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) external;
function getTokenDistributor() external view returns (address);
function setTokenDistributor(address _tokenDistributor) external;
function getFeeProvider() external view returns (address);
function setFeeProviderImpl(address _feeProvider) external;
function getLendingPoolLiquidationManager() external view returns (address);
function setLendingPoolLiquidationManager(address _manager) external;
function getLendingPoolManager() external view returns (address);
function setLendingPoolManager(address _lendingPoolManager) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address _priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address _lendingRateOracle) external;
}
| 9,805,924 |
./full_match/80001/0xd74B1EbE3f9bB0045d58d6Fe4B6380733a8656E9/sources/contracts/v1/SwylClub.sol | Lets an account start a new Club Start a new Club struct/ stop a club's owner to create a second club grant CLUB_OWNER_ROLE to the caller handle clubId and `totalNumberClubs` start a new Club Tier[] memory tiers; | function startClub(address _currency) external override {
require(!hasRole(CLUB_OWNER_ROLE, _msgSender()), "!NOT ALOOWED - account already has a club");
_setupRole(CLUB_OWNER_ROLE, _msgSender());
uint256 currentId = totalNumberClubs;
Club memory newClub = Club({
clubId: currentId,
clubOwner: _msgSender(),
date: block.timestamp,
currency: _currency,
totalMembers: 0
});
}
| 850,821 |
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title 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;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
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));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
contract ERC1820Registry {
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external;
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address);
function setManager(address _addr, address _newManager) external;
function getManager(address _addr) public view returns (address);
}
/// Base client to interact with the registry.
contract ERC1820Client {
ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation);
}
function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash);
}
function delegateManagement(address _newManager) internal {
ERC1820REGISTRY.setManager(address(this), _newManager);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
contract ERC1820Implementer {
bytes32 constant ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
mapping(bytes32 => bool) internal _interfaceHashes;
function canImplementInterfaceForAddress(bytes32 interfaceHash, address /*addr*/) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bytes32)
{
if(_interfaceHashes[interfaceHash]) {
return ERC1820_ACCEPT_MAGIC;
} else {
return "";
}
}
function _setInterface(string memory interfaceLabel) internal {
_interfaceHashes[keccak256(abi.encodePacked(interfaceLabel))] = true;
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400 security token standard
* @dev See https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md
*/
interface IERC1400 /*is IERC20*/ { // Interfaces can currently not inherit interfaces, but IERC1400 shall include IERC20
// ****************** Document Management *******************
function getDocument(bytes32 name) external view returns (string memory, bytes32);
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external;
// ******************* Token Information ********************
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256);
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory);
// *********************** Transfers ************************
function transferWithData(address to, uint256 value, bytes calldata data) external;
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external;
// *************** Partition Token Transfers ****************
function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32);
function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32);
// ****************** Controller Operation ******************
function isControllable() external view returns (bool);
// function controllerTransfer(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorTransferByPartition"
// function controllerRedeem(address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorRedeemByPartition"
// ****************** Operator Management *******************
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function authorizeOperatorByPartition(bytes32 partition, address operator) external;
function revokeOperatorByPartition(bytes32 partition, address operator) external;
// ****************** Operator Information ******************
function isOperator(address operator, address tokenHolder) external view returns (bool);
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool);
// ********************* Token Issuance *********************
function isIssuable() external view returns (bool);
function issue(address tokenHolder, uint256 value, bytes calldata data) external;
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external;
// ******************** Token Redemption ********************
function redeem(uint256 value, bytes calldata data) external;
function redeemFrom(address tokenHolder, uint256 value, bytes calldata data) external;
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external;
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external;
// ******************* Transfer Validity ********************
// We use different transfer validity functions because those described in the interface don't allow to verify the certificate's validity.
// Indeed, verifying the ecrtificate's validity requires to keeps the function's arguments in the exact same order as the transfer function.
//
// function canTransfer(address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferFrom(address from, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferByPartition(address from, address to, bytes32 partition, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32);
// ******************* Controller Events ********************
// We don't use this event as we don't use "controllerTransfer"
// event ControllerTransfer(
// address controller,
// address indexed from,
// address indexed to,
// uint256 value,
// bytes data,
// bytes operatorData
// );
//
// We don't use this event as we don't use "controllerRedeem"
// event ControllerRedemption(
// address controller,
// address indexed tokenHolder,
// uint256 value,
// bytes data,
// bytes operatorData
// );
// ******************** Document Events *********************
event Document(bytes32 indexed name, string uri, bytes32 documentHash);
// ******************** Transfer Events *********************
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event ChangedPartition(
bytes32 indexed fromPartition,
bytes32 indexed toPartition,
uint256 value
);
// ******************** Operator Events *********************
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
// ************** Issuance / Redemption Events **************
event Issued(address indexed operator, address indexed to, uint256 value, bytes data);
event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data);
event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData);
event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes operatorData);
}
/**
* Reason codes - ERC-1066
*
* To improve the token holder experience, canTransfer MUST return a reason byte code
* on success or failure based on the ERC-1066 application-specific status codes specified below.
* An implementation can also return arbitrary data as a bytes32 to provide additional
* information not captured by the reason code.
*
* Code Reason
* 0x50 transfer failure
* 0x51 transfer success
* 0x52 insufficient balance
* 0x53 insufficient allowance
* 0x54 transfers halted (contract paused)
* 0x55 funds locked (lockup period)
* 0x56 invalid sender
* 0x57 invalid receiver
* 0x58 invalid operator (transfer agent)
* 0x59
* 0x5a
* 0x5b
* 0x5a
* 0x5b
* 0x5c
* 0x5d
* 0x5e
* 0x5f token meta or info
*
* These codes are being discussed at: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/283/24
*/
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensValidator
* @dev ERC1400TokensValidator interface
*/
interface IERC1400TokensValidator {
function canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToValidate(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensChecker
* @dev IERC1400TokensChecker interface
*/
interface IERC1400TokensChecker {
// function canTransfer(
// bytes4 functionSig,
// address operator,
// address from,
// address to,
// uint256 value,
// bytes calldata data,
// bytes calldata operatorData
// ) external view returns (byte, bytes32);
function canTransferByPartition(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
) external view returns (byte, bytes32, bytes32);
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensSender
* @dev ERC1400TokensSender interface
*/
interface IERC1400TokensSender {
function canTransfer(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToTransfer(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensRecipient
* @dev ERC1400TokensRecipient interface
*/
interface IERC1400TokensRecipient {
function canReceive(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensReceived(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// Extensions (hooks triggered by the contract)
/**
* @title ERC1400
* @dev ERC1400 logic
*/
contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole {
using SafeMath for uint256;
// Token
string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token";
string constant internal ERC20_INTERFACE_NAME = "ERC20Token";
// Token extensions (hooks triggered by the contract)
string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker";
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
// User extensions (hooks triggered by the contract)
string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
/************************************* Token description ****************************************/
string internal _name;
string internal _symbol;
uint256 internal _granularity;
uint256 internal _totalSupply;
bool internal _migrated;
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
// Indicate whether the token can still be controlled by operators or not anymore.
bool internal _isControllable;
// Indicate whether the token can still be issued by the issuer or not anymore.
bool internal _isIssuable;
/************************************************************************************************/
/********************************** ERC20 Token mappings ****************************************/
// Mapping from tokenHolder to balance.
mapping(address => uint256) internal _balances;
// Mapping from (tokenHolder, spender) to allowed value.
mapping (address => mapping (address => uint256)) internal _allowed;
/************************************************************************************************/
/**************************************** Documents *********************************************/
struct Doc {
string docURI;
bytes32 docHash;
}
// Mapping for token URIs.
mapping(bytes32 => Doc) internal _documents;
/************************************************************************************************/
/*********************************** Partitions mappings ***************************************/
// List of partitions.
bytes32[] internal _totalPartitions;
// Mapping from partition to their index.
mapping (bytes32 => uint256) internal _indexOfTotalPartitions;
// Mapping from partition to global balance of corresponding partition.
mapping (bytes32 => uint256) internal _totalSupplyByPartition;
// Mapping from tokenHolder to their partitions.
mapping (address => bytes32[]) internal _partitionsOf;
// Mapping from (tokenHolder, partition) to their index.
mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf;
// Mapping from (tokenHolder, partition) to balance of corresponding partition.
mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition;
// List of token default partitions (for ERC20 compatibility).
bytes32[] internal _defaultPartitions;
/************************************************************************************************/
/********************************* Global operators mappings ************************************/
// Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC]
mapping(address => mapping(address => bool)) internal _authorizedOperator;
// Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
address[] internal _controllers;
// Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
mapping(address => bool) internal _isController;
/************************************************************************************************/
/******************************** Partition operators mappings **********************************/
// Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC]
mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition;
// Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC]
mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition;
// Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => address[]) internal _controllersByPartition;
// Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
/************************************************************************************************/
/***************************************** Modifiers ********************************************/
/**
* @dev Modifier to verify if token is issuable.
*/
modifier isIssuableToken() {
require(_isIssuable, "55"); // 0x55 funds locked (lockup period)
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not migrated.
*/
modifier isNotMigratedToken() {
require(!_migrated, "54"); // 0x54 transfers halted (contract paused)
_;
}
/************************************************************************************************/
/**************************** Events (additional - not mandatory) *******************************/
event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value);
/************************************************************************************************/
/**
* @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry.
* @param name Name of the token.
* @param symbol Symbol of the token.
* @param granularity Granularity of the token.
* @param controllers Array of initial controllers.
* @param defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions
)
public
{
_name = name;
_symbol = symbol;
_totalSupply = 0;
require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1
_granularity = granularity;
_setControllers(controllers);
_defaultPartitions = defaultPartitions;
_isControllable = true;
_isIssuable = true;
// Register contract in ERC1820 registry
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this));
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this));
// Indicate token verifies ERC1400 and ERC20 interfaces
ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration
ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/
/************************************************************************************************/
/**
* @dev Get the total number of issued tokens.
* @return Total supply of tokens currently in circulation.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Get the balance of the account with address 'tokenHolder'.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token held by 'tokenHolder' in the token contract.
*/
function balanceOf(address tokenHolder) external view returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev Transfer token for a specified address.
* @param to The address to transfer to.
* @param value The value to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, "");
return true;
}
/**
* @dev Check the value 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 value of tokens still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Approve 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.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address which you want to transfer tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/
/************************************************************************************************/
/************************************* Document Management **************************************/
/**
* @dev Access a document associated with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @return Requested document + document hash.
*/
function getDocument(bytes32 name) external view returns (string memory, bytes32) {
require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document
return (
_documents[name].docURI,
_documents[name].docHash
);
}
/**
* @dev Associate a document with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @param uri Document content.
* @param documentHash Hash of the document [optional parameter].
*/
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external {
require(_isController[msg.sender]);
_documents[name] = Doc({
docURI: uri,
docHash: documentHash
});
emit Document(name, uri, documentHash);
}
/************************************************************************************************/
/************************************** Token Information ***************************************/
/**
* @dev Get balance of a tokenholder for a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract.
*/
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256) {
return _balanceOfByPartition[tokenHolder][partition];
}
/**
* @dev Get partitions index of a tokenholder.
* @param tokenHolder Address for which the partitions index are returned.
* @return Array of partitions index of 'tokenHolder'.
*/
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory) {
return _partitionsOf[tokenHolder];
}
/************************************************************************************************/
/****************************************** Transfers *******************************************/
/**
* @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
*/
function transferWithData(address to, uint256 value, bytes calldata data) external {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, data);
}
/**
* @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'.
* @param from Token holder (or 'address(0)' to set from to 'msg.sender').
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from').
*/
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external {
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_transferByDefaultPartitions(msg.sender, from, to, value, data);
}
/************************************************************************************************/
/********************************** Partition Token Transfers ***********************************/
/**
* @dev Transfer tokens from a specific partition.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
* @return Destination partition.
*/
function transferByPartition(
bytes32 partition,
address to,
uint256 value,
bytes calldata data
)
external
returns (bytes32)
{
return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, "");
}
/**
* @dev Transfer tokens from a specific partition through an operator.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator.
* @return Destination partition.
*/
function operatorTransferByPartition(
bytes32 partition,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
)
external
returns (bytes32)
{
require(_isOperatorForPartition(partition, msg.sender, from)
|| (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowedByPartition[partition][from][msg.sender] >= value) {
_allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);
} else {
_allowedByPartition[partition][from][msg.sender] = 0;
}
return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);
}
/************************************************************************************************/
/************************************* Controller Operation *************************************/
/**
* @dev Know if the token can be controlled by operators.
* If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future.
* @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore.
*/
function isControllable() external view returns (bool) {
return _isControllable;
}
/************************************************************************************************/
/************************************* Operator Management **************************************/
/**
* @dev Set a third party operator address as an operator of 'msg.sender' to transfer
* and redeem tokens on its behalf.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperator(address operator) external {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = true;
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator for 'msg.sender'
* and to transfer and redeem tokens on its behalf.
* @param operator Address to rescind as an operator for 'msg.sender'.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = false;
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev Set 'operator' as an operator for 'msg.sender' for a given partition.
* @param partition Name of the partition.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperatorByPartition(bytes32 partition, address operator) external {
_authorizedOperatorByPartition[msg.sender][partition][operator] = true;
emit AuthorizedOperatorByPartition(partition, operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator on a given
* partition for 'msg.sender' and to transfer and redeem tokens on its behalf.
* @param partition Name of the partition.
* @param operator Address to rescind as an operator on given partition for 'msg.sender'.
*/
function revokeOperatorByPartition(bytes32 partition, address operator) external {
_authorizedOperatorByPartition[msg.sender][partition][operator] = false;
emit RevokedOperatorByPartition(partition, operator, msg.sender);
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of tokenHolder.
* @param tokenHolder Address of a token holder which may have the operator address as an operator.
* @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise.
*/
function isOperator(address operator, address tokenHolder) external view returns (bool) {
return _isOperator(operator, tokenHolder);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool) {
return _isOperatorForPartition(partition, operator, tokenHolder);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Know if new tokens can be issued in the future.
* @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore.
*/
function isIssuable() external view returns (bool) {
return _isIssuable;
}
/**
* @dev Issue tokens from default partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issue(address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
_issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data);
}
/**
* @dev Issue tokens from a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
{
_issueByPartition(partition, msg.sender, tokenHolder, value, data);
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Redeem the amount of tokens from the address 'msg.sender'.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption, by the token holder.
*/
function redeem(uint256 value, bytes calldata data)
external
{
_redeemByDefaultPartitions(msg.sender, msg.sender, value, data);
}
/**
* @dev Redeem the amount of tokens on behalf of the address from.
* @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender).
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function redeemFrom(address from, uint256 value, bytes calldata data)
external
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_redeemByDefaultPartitions(msg.sender, from, value, data);
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param value Number of tokens redeemed.
* @param data Information attached to the redemption, by the redeemer.
*/
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data)
external
{
_redeemByPartition(partition, msg.sender, msg.sender, value, data, "");
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to redeem tokens.
* @param value Number of tokens redeemed
* @param operatorData Information attached to the redemption, by the operator.
*/
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)
external
{
require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent)
_redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData);
}
/************************************************************************************************/
/************************************************************************************************/
/************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token description *****************************************/
/**
* @dev Get the name of the token, e.g., "MyToken".
* @return Name of the token.
*/
function name() external view returns(string memory) {
return _name;
}
/**
* @dev Get the symbol of the token, e.g., "MYT".
* @return Symbol of the token.
*/
function symbol() external view returns(string memory) {
return _symbol;
}
/**
* @dev Get the number of decimals of the token.
* @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400.
*/
function decimals() external pure returns(uint8) {
return uint8(18);
}
/**
* @dev Get the smallest part of the token that’s not divisible.
* @return The smallest non-divisible part of the token.
*/
function granularity() external view returns(uint256) {
return _granularity;
}
/**
* @dev Get list of existing partitions.
* @return Array of all exisiting partitions.
*/
function totalPartitions() external view returns (bytes32[] memory) {
return _totalPartitions;
}
/**
* @dev Get the total number of issued tokens for a given partition.
* @param partition Name of the partition.
* @return Total supply of tokens currently in circulation, for a given partition.
*/
function totalSupplyByPartition(bytes32 partition) external view returns (uint256) {
return _totalSupplyByPartition[partition];
}
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
/**
* @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders.
* Once set to false, '_isControllable' can never be set to 'true' again.
*/
function renounceControl() external onlyOwner {
_isControllable = false;
}
/**
* @dev Definitely renounce the possibility to issue new tokens.
* Once set to false, '_isIssuable' can never be set to 'true' again.
*/
function renounceIssuance() external onlyOwner {
_isIssuable = false;
}
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Get the list of controllers as defined by the token contract.
* @return List of addresses of all the controllers.
*/
function controllers() external view returns (address[] memory) {
return _controllers;
}
/**
* @dev Get controllers for a given partition.
* @param partition Name of the partition.
* @return Array of controllers for partition.
*/
function controllersByPartition(bytes32 partition) external view returns (address[] memory) {
return _controllersByPartition[partition];
}
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function setControllers(address[] calldata operators) external onlyOwner {
_setControllers(operators);
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner {
_setPartitionControllers(partition, operators);
}
/************************************************************************************************/
/********************************* Token default partitions *************************************/
/**
* @dev Get default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* For example, a security token may return the bytes32("unrestricted").
* @return Array of default partitions.
*/
function getDefaultPartitions() external view returns (bytes32[] memory) {
return _defaultPartitions;
}
/**
* @dev Set default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* @param partitions partitions to use by default when not specified.
*/
function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner {
_defaultPartitions = partitions;
}
/************************************************************************************************/
/******************************** Partition Token Allowances ************************************/
/**
* @dev Check the value of tokens that an owner allowed to a spender.
* @param partition Name of the partition.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the value of tokens still available for the spender.
*/
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) {
return _allowedByPartition[partition][owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param partition Name of the partition.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowedByPartition[partition][msg.sender][spender] = value;
emit ApprovalByPartition(partition, msg.sender, spender, value);
return true;
}
/************************************************************************************************/
/******************* Token extension (hooks triggered by the contract) **************************/
/**
* @dev Set validator contract address.
* The validator contract needs to verify "ERC1400TokensValidator" interface.
* Once setup, the validator will be called everytime a transfer is executed.
* @param validatorAddress Address of the validator contract.
* @param interfaceLabel Interface label of hook contract.
*/
function setHookContract(address validatorAddress, string calldata interfaceLabel) external onlyOwner {
_setHookContract(validatorAddress, interfaceLabel);
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function migrate(address newContractAddress, bool definitive) external onlyOwner {
_migrate(newContractAddress, definitive);
}
/************************************************************************************************/
/************************************************************************************************/
/************************************* INTERNAL FUNCTIONS ***************************************/
/************************************************************************************************/
/**************************************** Token Transfers ***************************************/
/**
* @dev Perform the transfer of tokens.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
*/
function _transferWithData(
address from,
address to,
uint256 value
)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value); // ERC20 retrocompatibility
}
/**
* @dev Transfer tokens from a specific partition.
* @param fromPartition Partition of the tokens to transfer.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return Destination partition.
*/
function _transferByPartition(
bytes32 fromPartition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
returns (bytes32)
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
bytes32 toPartition = fromPartition;
if(operatorData.length != 0 && data.length >= 64) {
toPartition = _getDestinationPartition(fromPartition, data);
}
_callPreTransferHooks(fromPartition, operator, from, to, value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_transferWithData(from, to, value);
_addTokenToPartition(to, toPartition, value);
_callPostTransferHooks(toPartition, operator, from, to, value, data, operatorData);
emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData);
if(toPartition != fromPartition) {
emit ChangedPartition(fromPartition, toPartition, value);
}
return toPartition;
}
/**
* @dev Transfer tokens from default partitions.
* Function used for ERC20 retrocompatibility.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION].
*/
function _transferByDefaultPartitions(
address operator,
address from,
address to,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, "");
_remainingValue = 0;
break;
} else if (_localBalance != 0) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/**
* @dev Retrieve the destination partition from the 'data' field.
* By convention, a partition change is requested ONLY when 'data' starts
* with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
* When the flag is detected, the destination tranche is extracted from the
* 32 bytes following the flag.
* @param fromPartition Partition of the tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @return Destination partition.
*/
function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) {
bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 flag;
assembly {
flag := mload(add(data, 32))
}
if(flag == changePartitionFlag) {
assembly {
toPartition := mload(add(data, 64))
}
} else {
toPartition = fromPartition;
}
}
/**
* @dev Remove a token from a specific partition.
* @param from Token holder.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
uint256 index1 = _indexOfTotalPartitions[partition];
require(index1 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing
_indexOfTotalPartitions[lastValue] = index1;
_totalPartitions.length -= 1;
_indexOfTotalPartitions[partition] = 0;
}
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
uint256 index2 = _indexOfPartitionsOf[from][partition];
require(index2 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing
_indexOfPartitionsOf[from][lastValue] = index2;
_partitionsOf[from].length -= 1;
_indexOfPartitionsOf[from][partition] = 0;
}
}
/**
* @dev Add a token to a specific partition.
* @param to Token recipient.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal {
if(value != 0) {
if (_indexOfPartitionsOf[to][partition] == 0) {
_partitionsOf[to].push(partition);
_indexOfPartitionsOf[to][partition] = _partitionsOf[to].length;
}
_balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value);
if (_indexOfTotalPartitions[partition] == 0) {
_totalPartitions.push(partition);
_indexOfTotalPartitions[partition] = _totalPartitions.length;
}
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value);
}
}
/**
* @dev Check if 'value' is multiple of the granularity.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of the granularity.
*/
function _isMultiple(uint256 value) internal view returns(bool) {
return(value.div(_granularity).mul(_granularity) == value);
}
/************************************************************************************************/
/****************************************** Hooks ***********************************************/
/**
* @dev Check for 'ERC1400TokensSender' hook on the sender + check for 'ERC1400TokensValidator' on the token
* contract address and call them.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callPreTransferHooks(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address senderImplementation;
senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER);
if (senderImplementation != address(0)) {
IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.sig, partition, operator, from, to, value, data, operatorData);
}
address validatorImplementation;
validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR);
if (validatorImplementation != address(0)) {
IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.sig, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensRecipient' hook on the recipient and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance increase (through transfer or issuance).
* @param from Token holder for a transfer and 0x for an issuance.
* @param to Token recipient.
* @param value Number of tokens the recipient balance is increased by.
* @param data Extra information, intended for the token holder ('from').
* @param operatorData Extra information attached by the operator (if any).
*/
function _callPostTransferHooks(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address recipientImplementation;
recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT);
if (recipientImplementation != address(0)) {
IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.sig, partition, operator, from, to, value, data, operatorData);
}
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of 'tokenHolder'.
* @param tokenHolder Address of a token holder which may have the 'operator' address as an operator.
* @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise.
*/
function _isOperator(address operator, address tokenHolder) internal view returns (bool) {
return (operator == tokenHolder
|| _authorizedOperator[operator][tokenHolder]
|| (_isControllable && _isController[operator])
);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) {
return (_isOperator(operator, tokenHolder)
|| _authorizedOperatorByPartition[tokenHolder][partition][operator]
|| (_isControllable && _isControllerByPartition[partition][operator])
);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Perform the issuance of tokens.
* @param operator Address which triggered the issuance.
* @param to Token recipient.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, and intended for the recipient (to).
*/
function _issue(address operator, address to, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Issued(operator, to, value, data);
emit Transfer(address(0), to, value); // ERC20 retrocompatibility
}
/**
* @dev Issue tokens from a specific partition.
* @param toPartition Name of the partition.
* @param operator The address performing the issuance.
* @param to Token recipient.
* @param value Number of tokens to issue.
* @param data Information attached to the issuance.
*/
function _issueByPartition(
bytes32 toPartition,
address operator,
address to,
uint256 value,
bytes memory data
)
internal
{
_issue(operator, to, value, data);
_addTokenToPartition(to, toPartition, value);
_callPostTransferHooks(toPartition, operator, address(0), to, value, data, "");
emit IssuedByPartition(toPartition, operator, to, value, data, "");
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Perform the token redemption.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeem(address operator, address from, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(from != address(0), "56"); // 0x56 invalid sender
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Redeemed(operator, from, value, data);
emit Transfer(from, address(0), value); // ERC20 retrocompatibility
}
/**
* @dev Redeem tokens of a specific partition.
* @param fromPartition Name of the partition.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
* @param operatorData Information attached to the redemption, by the operator (if any).
*/
function _redeemByPartition(
bytes32 fromPartition,
address operator,
address from,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
_callPreTransferHooks(fromPartition, operator, from, address(0), value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_redeem(operator, from, value, data);
emit RedeemedByPartition(fromPartition, operator, from, value, operatorData);
}
/**
* @dev Redeem tokens from a default partitions.
* @param operator The address performing the redeem.
* @param from Token holder.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeemByDefaultPartitions(
address operator,
address from,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, "");
_remainingValue = 0;
break;
} else {
_redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/************************************************************************************************/
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param functionSig ID of the function that needs to be called.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function _canTransfer(bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)
internal
view
returns (byte, bytes32, bytes32)
{
address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER);
if((checksImplementation != address(0))) {
return IERC1400TokensChecker(checksImplementation).canTransferByPartition(functionSig, partition, operator, from, to, value, data, operatorData);
}
else {
return(hex"00", "", partition);
}
}
/************************************************************************************************/
/************************************************************************************************/
/************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function _setControllers(address[] memory operators) internal {
for (uint i = 0; i<_controllers.length; i++){
_isController[_controllers[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isController[operators[j]] = true;
}
_controllers = operators;
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function _setPartitionControllers(bytes32 partition, address[] memory operators) internal {
for (uint i = 0; i<_controllersByPartition[partition].length; i++){
_isControllerByPartition[partition][_controllersByPartition[partition][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isControllerByPartition[partition][operators[j]] = true;
}
_controllersByPartition[partition] = operators;
}
/************************************************************************************************/
/******************* Token extension (hooks triggered by the contract) **************************/
/**
* @dev Set validator contract address.
* The validator contract needs to verify "ERC1400TokensValidator" interface.
* Once setup, the validator will be called everytime a transfer is executed.
* @param validatorAddress Address of the validator contract.
* @param interfaceLabel Interface label of hook contract.
*/
function _setHookContract(address validatorAddress, string memory interfaceLabel) internal {
address oldValidatorAddress = interfaceAddr(address(this), interfaceLabel);
if (oldValidatorAddress != address(0)) {
if(isMinter(oldValidatorAddress)) {
_removeMinter(oldValidatorAddress);
}
_isController[oldValidatorAddress] = false;
}
ERC1820Client.setInterfaceImplementation(interfaceLabel, validatorAddress);
if(!isMinter(validatorAddress)) {
_addMinter(validatorAddress);
}
_isController[validatorAddress] = true;
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function _migrate(address newContractAddress, bool definitive) internal {
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress);
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress);
if(definitive) {
_migrated = true;
}
}
/************************************************************************************************/
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// CertificateController comment...
contract CertificateController {
// If set to 'true', the certificate control is activated
bool _certificateControllerActivated;
// Address used by off-chain controller service to sign certificate
mapping(address => bool) internal _certificateSigners;
// A nonce used to ensure a certificate can be used only once
/* mapping(address => uint256) internal _checkCount; */
// A nonce used to ensure a certificate can be used only once
mapping(bytes32 => bool) internal _usedCertificate;
event Used(address sender);
constructor(address _certificateSigner, bool activated) public {
_setCertificateSigner(_certificateSigner, true);
_certificateControllerActivated = activated;
}
/**
* @dev Modifier to protect methods with certificate control
*/
modifier isValidCertificate(bytes memory data) {
if(_certificateControllerActivated) {
require(_certificateSigners[msg.sender] || _checkCertificate(data, 0, 0x00000000), "54"); // 0x54 transfers halted (contract paused)
bytes32 salt;
assembly {
salt := mload(add(data, 0x20))
}
_usedCertificate[salt] = true; // Use certificate
emit Used(msg.sender);
}
_;
}
/**
* @dev Modifier to protect methods with certificate control
*/
/* modifier isValidPayableCertificate(bytes memory data) {
require(_certificateSigners[msg.sender] || _checkCertificate(data, msg.value, 0x00000000), "54"); // 0x54 transfers halted (contract paused)
bytes32 salt;
assembly {
salt := mload(add(data, 0x20))
}
_usedCertificate[salt] = true; // Use certificate
emit Used(msg.sender);
_;
} */
/**
* @dev Get state of certificate (used or not).
* @param salt First 32 bytes of certificate whose validity is being checked.
* @return bool 'true' if certificate is already used, 'false' if not.
*/
function isUsedCertificate(bytes32 salt) external view returns (bool) {
return _usedCertificate[salt];
}
/**
* @dev Set signer authorization for operator.
* @param operator Address to add/remove as a certificate signer.
* @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not.
*/
function _setCertificateSigner(address operator, bool authorized) internal {
require(operator != address(0)); // Action Blocked - Not a valid address
_certificateSigners[operator] = authorized;
}
/**
* @dev Get activation status of certificate controller.
*/
function certificateControllerActivated() external view returns (bool) {
return _certificateControllerActivated;
}
/**
* @dev Activate/disactivate certificate controller.
* @param activated 'true', if the certificate control shall be activated, 'false' if not.
*/
function _setCertificateControllerActivated(bool activated) internal {
_certificateControllerActivated = activated;
}
/**
* @dev Checks if a certificate is correct
* @param data Certificate to control
*/
function _checkCertificate(
bytes memory data,
uint256 amount,
bytes4 functionID
)
internal
view
returns(bool)
{
bytes32 salt;
uint256 e;
bytes32 r;
bytes32 s;
uint8 v;
// Certificate should be 129 bytes long
if (data.length != 129) {
return false;
}
// Extract certificate information and expiration time from payload
assembly {
// Retrieve expirationTime & ECDSA elements from certificate which is a 97 long bytes
// Certificate encoding format is: <salt (32 bytes)>@<expirationTime (32 bytes)>@<r (32 bytes)>@<s (32 bytes)>@<v (1 byte)>
salt := mload(add(data, 0x20))
e := mload(add(data, 0x40))
r := mload(add(data, 0x60))
s := mload(add(data, 0x80))
v := byte(0, mload(add(data, 0xa0)))
}
// Certificate should not be expired
if (e < now) {
return false;
}
if (v < 27) {
v += 27;
}
// Perform ecrecover to ensure message information corresponds to certificate
if (v == 27 || v == 28) {
// Extract payload and remove data argument
bytes memory payload;
assembly {
let payloadsize := sub(calldatasize, 192)
payload := mload(0x40) // allocate new memory
mstore(0x40, add(payload, and(add(add(payloadsize, 0x20), 0x1f), not(0x1f)))) // boolean trick for padding to 0x40
mstore(payload, payloadsize) // set length
calldatacopy(add(add(payload, 0x20), 4), 4, sub(payloadsize, 4))
}
if(functionID == 0x00000000) {
assembly {
calldatacopy(add(payload, 0x20), 0, 4)
}
} else {
for (uint i = 0; i < 4; i++) { // replace 4 bytes corresponding to function selector
payload[i] = functionID[i];
}
}
// Pack and hash
bytes memory pack = abi.encodePacked(
msg.sender,
this,
amount,
payload,
e,
salt
);
bytes32 hash = keccak256(pack);
// Check if certificate match expected transactions parameters
if (_certificateSigners[ecrecover(hash, v, r, s)] && !_usedCertificate[salt]) {
return true;
}
}
return false;
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title ERC1400
* @dev ERC1400 logic
*/
contract ERC1400CertificateSalt is ERC1400, CertificateController {
/**
* @dev Initialize ERC1400 + initialize certificate controller.
* @param name Name of the token.
* @param symbol Symbol of the token.
* @param granularity Granularity of the token.
* @param controllers Array of initial controllers.
* @param certificateSigner Address of the off-chain service which signs the
* conditional ownership certificates required for token transfers, issuance,
* redemption (Cf. CertificateController.sol).
* @param certificateActivated If set to 'true', the certificate controller
* is activated at contract creation.
* @param defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
address certificateSigner,
bool certificateActivated,
bytes32[] memory defaultPartitions
)
public
ERC1400(name, symbol, granularity, controllers, defaultPartitions)
CertificateController(certificateSigner, certificateActivated)
{}
/************************************ Certificate control ***************************************/
/**
* @dev Add a certificate signer for the token.
* @param operator Address to set as a certificate signer.
* @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not.
*/
function setCertificateSigner(address operator, bool authorized) external onlyOwner {
_setCertificateSigner(operator, authorized);
}
/**
* @dev Activate/disactivate certificate controller.
* @param activated 'true', if the certificate control shall be activated, 'false' if not.
*/
function setCertificateControllerActivated(bool activated) external onlyOwner {
_setCertificateControllerActivated(activated);
}
/************************************************************************************************/
/********************** ERC1400 functions to control with certificate ***************************/
function transferWithData(address to, uint256 value, bytes calldata data)
external
isValidCertificate(data)
{
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, data);
}
function transferFromWithData(address from, address to, uint256 value, bytes calldata data)
external
isValidCertificate(data)
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_transferByDefaultPartitions(msg.sender, from, to, value, data);
}
function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data)
external
isValidCertificate(data)
returns (bytes32)
{
return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, "");
}
function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData)
external
isValidCertificate(operatorData)
returns (bytes32)
{
require(_isOperatorForPartition(partition, msg.sender, from)
|| (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowedByPartition[partition][from][msg.sender] >= value) {
_allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);
} else {
_allowedByPartition[partition][from][msg.sender] = 0;
}
return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);
}
function issue(address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
isValidCertificate(data)
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
_issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data);
}
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data)
external
onlyMinter
isIssuableToken
isValidCertificate(data)
{
_issueByPartition(partition, msg.sender, tokenHolder, value, data);
}
function redeem(uint256 value, bytes calldata data)
external
isValidCertificate(data)
{
_redeemByDefaultPartitions(msg.sender, msg.sender, value, data);
}
function redeemFrom(address from, uint256 value, bytes calldata data)
external
isValidCertificate(data)
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_redeemByDefaultPartitions(msg.sender, from, value, data);
}
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data)
external
isValidCertificate(data)
{
_redeemByPartition(partition, msg.sender, msg.sender, value, data, "");
}
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)
external
isValidCertificate(operatorData)
{
require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent)
_redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData);
}
/************************************************************************************************/
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE]
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data)
external
view
returns (byte, bytes32, bytes32)
{
bytes4 functionSig = this.transferByPartition.selector; // 0xf3d490db: 4 first bytes of keccak256(transferByPartition(bytes32,address,uint256,bytes))
if(!_checkCertificate(data, 0, functionSig)) {
return(hex"54", "", partition); // 0x54 transfers halted (contract paused)
} else {
return ERC1400._canTransfer(functionSig, partition, msg.sender, msg.sender, to, value, data, "");
}
}
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE]
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData)
external
view
returns (byte, bytes32, bytes32)
{
bytes4 functionSig = this.operatorTransferByPartition.selector; // 0x8c0dee9c: 4 first bytes of keccak256(operatorTransferByPartition(bytes32,address,address,uint256,bytes,bytes))
if(!_checkCertificate(operatorData, 0, functionSig)) {
return(hex"54", "", partition); // 0x54 transfers halted (contract paused)
} else {
return ERC1400._canTransfer(functionSig, partition, msg.sender, from, to, value, data, operatorData);
}
}
/************************************************************************************************/
/******************* Token extension (hooks triggered by the contract) **************************/
/**
* @dev Set validator contract address.
* The validator contract needs to verify "ERC1400TokensValidator" interface.
* Once setup, the validator will be called everytime a transfer is executed.
* @param validatorAddress Address of the validator contract.
* @param interfaceLabel Interface label of hook contract.
*/
function _setHookContract(address validatorAddress, string memory interfaceLabel) internal {
address oldValidatorAddress = interfaceAddr(address(this), interfaceLabel);
_setCertificateSigner(oldValidatorAddress, false);
ERC1400._setHookContract(validatorAddress, interfaceLabel);
_setCertificateSigner(validatorAddress, true);
}
/************************************************************************************************/
} | Token extension (hooks triggered by the contract) / Set validator contract address. The validator contract needs to verify "ERC1400TokensValidator" interface. Once setup, the validator will be called everytime a transfer is executed. validatorAddress Address of the validator contract. interfaceLabel Interface label of hook contract./ | function _setHookContract(address validatorAddress, string memory interfaceLabel) internal {
address oldValidatorAddress = interfaceAddr(address(this), interfaceLabel);
_setCertificateSigner(oldValidatorAddress, false);
ERC1400._setHookContract(validatorAddress, interfaceLabel);
_setCertificateSigner(validatorAddress, true);
}
| 14,347,730 |