file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2021-11-24
*/
// Copyright (c) 2021 EverRise Pte Ltd. All rights reserved.
// EverRise licenses this file to you under the MIT license.
/*
The EverRise token is the keystone in the EverRise Ecosytem of dApps
and the overaching key that unlocks multi-blockchain unification via
the EverBridge.
On EverRise token txns 6% buyback and business development fees are collected
* 4% for token Buyback from the market,
with bought back tokens directly distributed as staking rewards
* 2% for Business Development (Development, Sustainability and Marketing)
________ _______ __
/ | / \ / |
$$$$$$$$/__ __ ______ ______ $$$$$$$ |$$/ _______ ______
$$ |__ / \ / |/ \ / \ $$ |__$$ |/ | / | / \
$$ | $$ \ /$$//$$$$$$ |/$$$$$$ |$$ $$< $$ |/$$$$$$$/ /$$$$$$ |
$$$$$/ $$ /$$/ $$ $$ |$$ | $$/ $$$$$$$ |$$ |$$ \ $$ $$ |
$$ |_____ $$ $$/ $$$$$$$$/ $$ | $$ | $$ |$$ | $$$$$$ |$$$$$$$$/
$$ | $$$/ $$ |$$ | $$ | $$ |$$ |/ $$/ $$ |
$$$$$$$$/ $/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
Learn more about EverRise and the EverRise Ecosystem of dApps and
how our utilities, and our partners, can help protect your investors
and help your project grow: https://www.everrise.com
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.8;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function transferFromWithPermit(
address sender,
address recipient,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
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);
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
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 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 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;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
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 DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view 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 name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function 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 removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function factory() external pure returns (address);
function WETH() external pure returns (address);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
interface IEverStake {
function createRewards(address acount, uint256 tAmount) external;
function deliver(uint256 tAmount) external;
function getTotalAmountStaked() external view returns (uint256);
function getTotalRewardsDistributed() external view returns (uint256);
}
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;
}
}
// helper methods for discovering LP pair addresses
library PairHelper {
bytes private constant token0Selector =
abi.encodeWithSelector(IUniswapV2Pair.token0.selector);
bytes private constant token1Selector =
abi.encodeWithSelector(IUniswapV2Pair.token1.selector);
function token0(address pair) internal view returns (address) {
return token(pair, token0Selector);
}
function token1(address pair) internal view returns (address) {
return token(pair, token1Selector);
}
function token(address pair, bytes memory selector)
private
view
returns (address)
{
// Do not check if pair is not a contract to avoid warning in txn log
if (!isContract(pair)) return address(0);
(bool success, bytes memory data) = pair.staticcall(selector);
if (success && data.length >= 32) {
return abi.decode(data, (address));
}
return address(0);
}
function isContract(address account) private view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(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;
address private _buybackOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier onlyBuybackOwner() {
require(
_buybackOwner == _msgSender(),
"Ownable: caller is not the buyback owner"
);
_;
}
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
_buybackOwner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
// Allow contract ownership and access to contract onlyOwner functions
// to be locked using EverOwn with control gated by community vote.
//
// EverRise ($RISE) stakers become voting members of the
// decentralized autonomous organization (DAO) that controls access
// to the token contract via the EverRise Ecosystem dApp EverOwn
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function transferBuybackOwnership(address newOwner)
external
virtual
onlyOwner
{
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_buybackOwner, newOwner);
_buybackOwner = newOwner;
}
function owner() public view returns (address) {
return _owner;
}
function buybackOwner() public view returns (address) {
return _buybackOwner;
}
}
contract EverRise is Context, IERC20, Ownable {
using SafeMath for uint256;
using PairHelper for address;
struct TransferDetails {
uint112 balance0;
uint112 balance1;
uint32 blockNumber;
address to;
address origin;
}
address payable public businessDevelopmentAddress =
payable(0x23F4d6e1072E42e5d25789e3260D19422C2d3674); // Business Development Address
address public stakingAddress;
address public everMigrateAddress;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private lastCoolDownTrade;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isEverRiseEcosystemContract;
address[] public allEcosystemContracts;
mapping(address => bool) private _isAuthorizedSwapToken;
address[] public allAuthorizedSwapTokens;
uint256 private constant MAX = ~uint256(0);
string private constant _name = "EverRise";
string private constant _symbol = "RISE";
// Large data type for maths
uint256 private constant _decimals = 18;
// Short data type for decimals function (no per function conversion)
uint8 private constant _decimalsShort = uint8(_decimals);
// Golden supply
uint256 private constant _tTotal = 7_1_618_033_988 * 10**_decimals;
uint256 private _holders = 0;
// Fee and max txn are set by setTradingEnabled
// to allow upgrading balances to arrange their wallets
// and stake their assets before trading start
uint256 public liquidityFee = 0;
uint256 private _previousLiquidityFee = liquidityFee;
uint256 private _maxTxAmount = _tTotal;
uint256 private constant _tradeStartLiquidityFee = 6;
uint256 private _tradeStartMaxTxAmount = _tTotal.div(1000); // Max txn 0.1% of supply
uint256 public businessDevelopmentDivisor = 2;
uint256 private minimumTokensBeforeSwap = 5 * 10**6 * 10**_decimals;
uint256 private buyBackUpperLimit = 10 * 10**18;
uint256 private buyBackTriggerTokenLimit = 1 * 10**6 * 10**_decimals;
uint256 private buyBackMinAvailability = 1 * 10**18; //1 BNB
uint256 private buyVolume = 0;
uint256 private sellVolume = 0;
uint256 public totalBuyVolume = 0;
uint256 public totalSellVolume = 0;
uint256 public totalVolume = 0;
uint256 private nextBuybackAmount = 0;
uint256 private buyBackTriggerVolume = 100 * 10**6 * 10**_decimals;
uint256 private tradingStart = MAX;
uint256 private tradingStartCooldown = MAX;
// 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.
uint256 private constant _FALSE = 1;
uint256 private constant _TRUE = 2;
uint256 private _checkingTokens;
uint256 private _inSwapAndLiquify;
// Infrequently set booleans
bool public swapAndLiquifyEnabled = false;
bool public buyBackEnabled = false;
bool public liquidityLocked = false;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
IEverStake stakeToken;
bytes32 public immutable DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
TransferDetails lastTransfer;
event BuyBackEnabledUpdated(bool enabled);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event SwapETHForTokens(uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
event SwapTokensForTokens(uint256 amountIn, address[] path);
event ExcludeFromFeeUpdated(address account);
event IncludeInFeeUpdated(address account);
event LiquidityFeeUpdated(uint256 prevValue, uint256 newValue);
event MaxTxAmountUpdated(uint256 prevValue, uint256 newValue);
event BusinessDevelopmentDivisorUpdated(
uint256 prevValue,
uint256 newValue
);
event MinTokensBeforeSwapUpdated(uint256 prevValue, uint256 newValue);
event BuybackMinAvailabilityUpdated(uint256 prevValue, uint256 newValue);
event TradingEnabled();
event BuyBackAndRewardStakers(uint256 amount);
event BuybackUpperLimitUpdated(uint256 prevValue, uint256 newValue);
event BuyBackTriggerTokenLimitUpdated(uint256 prevValue, uint256 newValue);
event RouterAddressUpdated(address prevAddress, address newAddress);
event BusinessDevelopmentAddressUpdated(
address prevAddress,
address newAddress
);
event StakingAddressUpdated(address prevAddress, address newAddress);
event EverMigrateAddressUpdated(address prevAddress, address newAddress);
event EverRiseEcosystemContractAdded(address contractAddress);
event EverRiseEcosystemContractRemoved(address contractAddress);
event HoldersIncreased(uint256 prevValue, uint256 newValue);
event HoldersDecreased(uint256 prevValue, uint256 newValue);
event AuthorizedSwapTokenAdded(address tokenAddress);
event AuthorizedSwapTokenRemoved(address tokenAddress);
event LiquidityLocked();
event LiquidityUnlocked();
event StakingIncreased(uint256 amount);
event StakingDecreased(uint256 amount);
modifier lockTheSwap() {
require(_inSwapAndLiquify != _TRUE);
_inSwapAndLiquify = _TRUE;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_inSwapAndLiquify = _FALSE;
}
modifier tokenCheck() {
require(_checkingTokens != _TRUE);
_checkingTokens = _TRUE;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_checkingTokens = _FALSE;
}
constructor(address _stakingAddress, address routerAddress) {
require(
_stakingAddress != address(0),
"_stakingAddress should not be to the zero address"
);
require(
routerAddress != address(0),
"routerAddress should not be the zero address"
);
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to modifiers 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.
_checkingTokens = _FALSE;
_inSwapAndLiquify = _FALSE;
stakingAddress = _stakingAddress;
stakeToken = IEverStake(_stakingAddress);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(routerAddress);
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); //Pancakeswap router mainnet - BSC
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); //Testnet
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); //Sushiswap router mainnet - Polygon
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uniswap V2 router mainnet - ETH
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xa5e0829caced8ffdd4de3c43696c57f7d7a678ff); //Quickswap V2 router mainnet - Polygon
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(_name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
_tOwned[_msgSender()] = _tTotal;
// Track holder change
_holders = 1;
emit HoldersIncreased(0, 1);
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_everRiseEcosystemContractAdd(_stakingAddress);
authorizedSwapTokenAdd(address(this));
authorizedSwapTokenAdd(uniswapV2Router.WETH());
emit Transfer(address(0), _msgSender(), _tTotal);
lockLiquidity();
}
// Function to receive ETH when msg.data is be empty
// Receives ETH from uniswapV2Router when swapping
receive() external payable {}
// Fallback function to receive ETH when msg.data is not empty
fallback() external payable {}
function transferBalance() external onlyOwner {
_msgSender().transfer(address(this).balance);
}
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function approve(address spender, uint256 amount)
external
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function transferFromWithPermit(
address sender,
address recipient,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (bool) {
permit(sender, _msgSender(), amount, deadline, v, r, s);
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function manualBuyback(uint256 amount, uint256 numOfDecimals)
external
onlyBuybackOwner
{
require(amount > 0 && numOfDecimals >= 0, "Invalid Input");
uint256 value = amount.mul(10**18).div(10**numOfDecimals);
uint256 tokensReceived = swapETHForTokensNoFee(
address(this),
stakingAddress,
value
);
//Distribute the rewards to the staking pool
distributeStakingRewards(tokensReceived);
}
function swapTokens(
address fromToken,
address toToken,
uint256 amount,
uint256 numOfDecimals,
uint256 fromTokenDecimals
) external onlyBuybackOwner {
require(_isAuthorizedSwapToken[fromToken], "fromToken is not an authorized token");
require(_isAuthorizedSwapToken[toToken], "toToken is not an authorized token");
uint256 actualAmount = amount
.mul(10**fromTokenDecimals)
.div(10**numOfDecimals);
if (toToken == uniswapV2Router.WETH()) {
swapTokensForEth(fromToken, address(this), actualAmount);
} else if (fromToken == uniswapV2Router.WETH()) {
swapETHForTokens(toToken, address(this), actualAmount);
} else {
swapTokensForTokens(
fromToken,
toToken,
address(this),
actualAmount
);
}
}
function lockLiquidity() public onlyOwner {
liquidityLocked = true;
emit LiquidityLocked();
}
function unlockLiquidity() external onlyOwner {
liquidityLocked = false;
emit LiquidityUnlocked();
}
function excludeFromFee(address account) external onlyOwner {
require(
!_isExcludedFromFee[account],
"Account is not excluded for fees"
);
_excludeFromFee(account);
}
function includeInFee(address account) external onlyOwner {
require(
_isExcludedFromFee[account],
"Account is not included for fees"
);
_includeInFee(account);
}
function setLiquidityFeePercent(uint256 liquidityFeeRate) external onlyOwner {
require(liquidityFeeRate <= 10, "liquidityFeeRate should be less than 10%");
uint256 prevValue = liquidityFee;
liquidityFee = liquidityFeeRate;
emit LiquidityFeeUpdated(prevValue, liquidityFee);
}
function setMaxTxAmount(uint256 txAmount) external onlyOwner {
uint256 prevValue = _maxTxAmount;
_maxTxAmount = txAmount;
emit MaxTxAmountUpdated(prevValue, txAmount);
}
function setBusinessDevelopmentDivisor(uint256 divisor) external onlyOwner {
require(
divisor <= liquidityFee,
"Business Development divisor should be less than liquidity fee"
);
uint256 prevValue = businessDevelopmentDivisor;
businessDevelopmentDivisor = divisor;
emit BusinessDevelopmentDivisorUpdated(
prevValue,
businessDevelopmentDivisor
);
}
function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap)
external
onlyOwner
{
uint256 prevValue = minimumTokensBeforeSwap;
minimumTokensBeforeSwap = _minimumTokensBeforeSwap;
emit MinTokensBeforeSwapUpdated(prevValue, minimumTokensBeforeSwap);
}
function setBuybackUpperLimit(uint256 buyBackLimit, uint256 numOfDecimals)
external
onlyBuybackOwner
{
uint256 prevValue = buyBackUpperLimit;
buyBackUpperLimit = buyBackLimit
.mul(10**18)
.div(10**numOfDecimals);
emit BuybackUpperLimitUpdated(prevValue, buyBackUpperLimit);
}
function setBuybackTriggerTokenLimit(uint256 buyBackTriggerLimit)
external
onlyBuybackOwner
{
uint256 prevValue = buyBackTriggerTokenLimit;
buyBackTriggerTokenLimit = buyBackTriggerLimit;
emit BuyBackTriggerTokenLimitUpdated(
prevValue,
buyBackTriggerTokenLimit
);
}
function setBuybackMinAvailability(uint256 amount, uint256 numOfDecimals)
external
onlyBuybackOwner
{
uint256 prevValue = buyBackMinAvailability;
buyBackMinAvailability = amount
.mul(10**18)
.div(10**numOfDecimals);
emit BuybackMinAvailabilityUpdated(prevValue, buyBackMinAvailability);
}
function setBuyBackEnabled(bool _enabled) public onlyBuybackOwner {
buyBackEnabled = _enabled;
emit BuyBackEnabledUpdated(_enabled);
}
function setTradingEnabled(uint256 _tradeStartDelay, uint256 _tradeStartCoolDown) external onlyOwner {
require(_tradeStartDelay < 10, "tradeStartDelay should be less than 10 minutes");
require(_tradeStartCoolDown < 120, "tradeStartCoolDown should be less than 120 minutes");
require(_tradeStartDelay < _tradeStartCoolDown, "tradeStartDelay must be less than tradeStartCoolDown");
// Can only be called once
require(tradingStart == MAX && tradingStartCooldown == MAX, "Trading has already started");
// Set initial values
liquidityFee = _tradeStartLiquidityFee;
_previousLiquidityFee = liquidityFee;
_maxTxAmount = _tradeStartMaxTxAmount;
setBuyBackEnabled(true);
setSwapAndLiquifyEnabled(true);
// Add time buffer to allow switching on trading on every chain
// before announcing to community
tradingStart = block.timestamp + _tradeStartDelay * 1 minutes;
tradingStartCooldown = tradingStart + _tradeStartCoolDown * 1 minutes;
// Announce to blockchain immediately, even though trades
// can't start until delay passes (snipers no sniping)
emit TradingEnabled();
}
function setBusinessDevelopmentAddress(address _businessDevelopmentAddress)
external
onlyOwner
{
require(
_businessDevelopmentAddress != address(0),
"_businessDevelopmentAddress should not be the zero address"
);
address prevAddress = businessDevelopmentAddress;
businessDevelopmentAddress = payable(_businessDevelopmentAddress);
emit BusinessDevelopmentAddressUpdated(
prevAddress,
_businessDevelopmentAddress
);
}
function setEverMigrateAddress(address _everMigrateAddress)
external
onlyOwner
{
require(
_everMigrateAddress != address(0),
"_everMigrateAddress should not be the zero address"
);
address prevAddress = everMigrateAddress;
everMigrateAddress = _everMigrateAddress;
emit EverMigrateAddressUpdated(prevAddress, _everMigrateAddress);
_everRiseEcosystemContractAdd(_everMigrateAddress);
}
function setStakingAddress(address _stakingAddress) external onlyOwner {
require(
_stakingAddress != address(0),
"_stakingAddress should not be to zero address"
);
address prevAddress = stakingAddress;
stakingAddress = _stakingAddress;
stakeToken = IEverStake(_stakingAddress);
emit StakingAddressUpdated(prevAddress, _stakingAddress);
_everRiseEcosystemContractAdd(_stakingAddress);
}
function setRouterAddress(address routerAddress) external onlyOwner {
require(
routerAddress != address(0),
"routerAddress should not be the zero address"
);
address prevAddress = address(uniswapV2Router);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(routerAddress);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
emit RouterAddressUpdated(prevAddress, routerAddress);
}
function everRiseEcosystemContractAdd(address contractAddress) external onlyOwner {
require(contractAddress != address(0), "contractAddress should not be the zero address");
require(contractAddress != address(this), "EverRise token should not be added as an Ecosystem contract");
require(
!_isEverRiseEcosystemContract[contractAddress],
"contractAddress is already included as an EverRise Ecosystem contract"
);
_everRiseEcosystemContractAdd(contractAddress);
}
function everRiseEcosystemContractRemove(address contractAddress) external onlyOwner {
require(
_isEverRiseEcosystemContract[contractAddress],
"contractAddress is not included as EverRise Ecosystem contract"
);
_isEverRiseEcosystemContract[contractAddress] = false;
for (uint256 i = 0; i < allEcosystemContracts.length; i++) {
if (allEcosystemContracts[i] == contractAddress) {
allEcosystemContracts[i] = allEcosystemContracts[allEcosystemContracts.length - 1];
allEcosystemContracts.pop();
break;
}
}
emit EverRiseEcosystemContractRemoved(contractAddress);
_includeInFee(contractAddress);
}
function balanceOf(address account)
external
view
override
returns (uint256)
{
uint256 balance0 = _balanceOf(account);
if (
!inSwapAndLiquify() &&
lastTransfer.blockNumber == uint32(block.number) &&
account == lastTransfer.to
) {
// Balance being checked is same address as last to in _transfer
// check if likely same txn and a Liquidity Add
_validateIfLiquidityAdd(account, uint112(balance0));
}
return balance0;
}
function maxTxAmount() external view returns (uint256) {
if (isTradingEnabled() && inTradingStartCoolDown()) {
uint256 maxTxn = maxTxCooldownAmount();
return maxTxn < _maxTxAmount ? maxTxn : _maxTxAmount;
}
return _maxTxAmount;
}
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function getTotalAmountStaked() external view returns (uint256)
{
return stakeToken.getTotalAmountStaked();
}
function getTotalRewardsDistributed() external view returns (uint256)
{
return stakeToken.getTotalRewardsDistributed();
}
function holders() external view returns (uint256) {
return _holders;
}
function minimumTokensBeforeSwapAmount() external view returns (uint256) {
return minimumTokensBeforeSwap;
}
function buyBackUpperLimitAmount() external view returns (uint256) {
return buyBackUpperLimit;
}
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[account];
}
function allEcosystemContractsLength() external view returns (uint) {
return allEcosystemContracts.length;
}
function allAuthorizedSwapTokensLength() external view returns (uint) {
return allAuthorizedSwapTokens.length;
}
function totalSupply() external pure override returns (uint256) {
return _tTotal;
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimalsShort;
}
function authorizedSwapTokenAdd(address tokenAddress) public onlyOwner {
require(tokenAddress != address(0), "tokenAddress should not be the zero address");
require(!_isAuthorizedSwapToken[tokenAddress], "tokenAddress is already an authorized token");
_isAuthorizedSwapToken[tokenAddress] = true;
allAuthorizedSwapTokens.push(tokenAddress);
emit AuthorizedSwapTokenAdded(tokenAddress);
}
function authorizedSwapTokenRemove(address tokenAddress) public onlyOwner {
require(tokenAddress != address(this), "cannot remove this contract from authorized tokens");
require(tokenAddress != uniswapV2Router.WETH(), "cannot remove the WETH type contract from authorized tokens");
require(_isAuthorizedSwapToken[tokenAddress], "tokenAddress is not an authorized token");
_isAuthorizedSwapToken[tokenAddress] = false;
for (uint256 i = 0; i < allAuthorizedSwapTokens.length; i++) {
if (allAuthorizedSwapTokens[i] == tokenAddress) {
allAuthorizedSwapTokens[i] = allAuthorizedSwapTokens[allAuthorizedSwapTokens.length - 1];
allAuthorizedSwapTokens.pop();
break;
}
}
emit AuthorizedSwapTokenRemoved(tokenAddress);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function isTradingEnabled() public view returns (bool) {
// Trading has been set and has time buffer has elapsed
return tradingStart < block.timestamp;
}
function inTradingStartCoolDown() public view returns (bool) {
// Trading has been started and the cool down period has elapsed
return tradingStartCooldown >= block.timestamp;
}
function maxTxCooldownAmount() public pure returns (uint256) {
return _tTotal.div(2000);
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(from != to, "Transfer to and from addresses the same");
require(!inTokenCheck(), "Invalid reentrancy from token0/token1 balanceOf check");
address _owner = owner();
bool isIgnoredAddress = from == _owner || to == _owner ||
_isEverRiseEcosystemContract[from] || _isEverRiseEcosystemContract[to];
bool _isTradingEnabled = isTradingEnabled();
require(amount <= _maxTxAmount || isIgnoredAddress || !_isTradingEnabled,
"Transfer amount exceeds the maxTxAmount");
address _pair = uniswapV2Pair;
require(_isTradingEnabled || isIgnoredAddress || (from != _pair && to != _pair),
"Trading is not enabled");
bool notInSwapAndLiquify = !inSwapAndLiquify();
if (_isTradingEnabled && inTradingStartCoolDown() && !isIgnoredAddress && notInSwapAndLiquify) {
validateDuringTradingCoolDown(to, from, amount);
}
uint256 contractTokenBalance = _balanceOf(address(this));
bool overMinimumTokenBalance = contractTokenBalance >=
minimumTokensBeforeSwap;
bool contractAction = _isTradingEnabled &&
notInSwapAndLiquify &&
swapAndLiquifyEnabled &&
to == _pair;
// Following block is for the contract to convert the tokens to ETH and do the buy back
if (contractAction) {
if (overMinimumTokenBalance) {
contractTokenBalance = minimumTokensBeforeSwap;
swapTokens(contractTokenBalance);
}
if (buyBackEnabled &&
address(this).balance > buyBackMinAvailability &&
buyVolume.add(sellVolume) > buyBackTriggerVolume
) {
if (nextBuybackAmount > address(this).balance) {
// Don't try to buyback more than is available.
// For example some "ETH" balance may have been
// temporally switched to stable coin in crypto-market
// downturn using swapTokens, for switching back later
nextBuybackAmount = address(this).balance;
}
if (nextBuybackAmount > 0) {
uint256 tokensReceived = buyBackTokens(nextBuybackAmount);
//Distribute the rewards to the staking pool
distributeStakingRewards(tokensReceived);
nextBuybackAmount = 0; //reset the next buyback amount
buyVolume = 0; //reset the buy volume
sellVolume = 0; // reset the sell volume
}
}
}
if (_isTradingEnabled) {
// Compute Sell Volume and set the next buyback amount
if (to == _pair) {
sellVolume = sellVolume.add(amount);
totalSellVolume = totalSellVolume.add(amount);
if (amount > buyBackTriggerTokenLimit) {
uint256 balance = address(this).balance;
if (balance > buyBackUpperLimit) balance = buyBackUpperLimit;
nextBuybackAmount = nextBuybackAmount.add(balance.div(100));
}
}
// Compute Buy Volume
else if (from == _pair) {
buyVolume = buyVolume.add(amount);
totalBuyVolume = totalBuyVolume.add(amount);
}
totalVolume = totalVolume.add(amount);
}
bool takeFee = true;
// If any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
// For safety Liquidity Adds should only be done by an owner,
// and transfers to and from EverRise Ecosystem contracts
// are not considered LP adds
if (isIgnoredAddress || buybackOwner() == _msgSender()) {
// Clear transfer data
_clearTransferIfNeeded();
} else if (notInSwapAndLiquify) {
// Not in a swap during a LP add, so record the transfer details
_recordPotentialLiquidityAddTransaction(to);
}
_tokenTransfer(from, to, amount, takeFee);
}
function _recordPotentialLiquidityAddTransaction(address to)
private
tokenCheck {
uint112 balance0 = uint112(_balanceOf(to));
address token1 = to.token1();
if (token1 == address(this)) {
// Switch token so token1 is always other side of pair
token1 = to.token0();
}
uint112 balance1;
if (token1 == address(0)) {
// Not a LP pair, or not yet (contract being created)
balance1 = 0;
} else {
balance1 = uint112(IERC20(token1).balanceOf(to));
}
lastTransfer = TransferDetails({
balance0: balance0,
balance1: balance1,
blockNumber: uint32(block.number),
to: to,
origin: tx.origin
});
}
function _clearTransferIfNeeded() private {
// Not Liquidity Add or is owner, clear data from same block to allow balanceOf
if (lastTransfer.blockNumber == uint32(block.number)) {
// Don't need to clear if different block
lastTransfer = TransferDetails({
balance0: 0,
balance1: 0,
blockNumber: 0,
to: address(0),
origin: address(0)
});
}
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(address(this), address(this), contractTokenBalance);
uint256 transferredBalance = address(this).balance.sub(initialBalance);
//Send to Business Development address
transferToAddressETH(
businessDevelopmentAddress,
transferredBalance
.mul(businessDevelopmentDivisor)
.div(liquidityFee)
);
}
function buyBackTokens(uint256 amount)
private
lockTheSwap
returns (uint256)
{
uint256 tokensReceived;
if (amount > 0) {
tokensReceived = swapETHForTokensNoFee(
address(this),
stakingAddress,
amount
);
}
return tokensReceived;
}
function swapTokensForEth(
address tokenAddress,
address toAddress,
uint256 tokenAmount
) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = tokenAddress;
path[1] = uniswapV2Router.WETH();
IERC20(tokenAddress).approve(address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
toAddress, // The contract
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function swapETHForTokensNoFee(
address tokenAddress,
address toAddress,
uint256 amount
) private returns (uint256) {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = tokenAddress;
// make the swap
uint256[] memory amounts = uniswapV2Router.swapExactETHForTokens{
value: amount
}(
0, // accept any amount of Tokens
path,
toAddress, // The contract
block.timestamp.add(300)
);
emit SwapETHForTokens(amount, path);
return amounts[1];
}
function swapETHForTokens(
address tokenAddress,
address toAddress,
uint256 amount
) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = tokenAddress;
// make the swap
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(
0, // accept any amount of Tokens
path,
toAddress, // The contract
block.timestamp.add(300)
);
emit SwapETHForTokens(amount, path);
}
function swapTokensForTokens(
address fromTokenAddress,
address toTokenAddress,
address toAddress,
uint256 tokenAmount
) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](3);
path[0] = fromTokenAddress;
path[1] = uniswapV2Router.WETH();
path[2] = toTokenAddress;
IERC20(fromTokenAddress).approve(address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of Tokens
path,
toAddress, // The contract
block.timestamp.add(120)
);
emit SwapTokensForTokens(tokenAmount, path);
}
function distributeStakingRewards(uint256 amount) private {
if (amount > 0) {
stakeToken.createRewards(address(this), amount);
stakeToken.deliver(amount);
emit BuyBackAndRewardStakers(amount);
}
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_actualTokenTransfer(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _actualTokenTransfer(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 tTransferAmount,
uint256 tLiquidity
) = _getValues(tAmount);
uint256 senderBefore = _tOwned[sender];
uint256 senderAfter = senderBefore.sub(tAmount);
_tOwned[sender] = senderAfter;
uint256 recipientBefore = _tOwned[recipient];
uint256 recipientAfter = recipientBefore.add(tTransferAmount);
_tOwned[recipient] = recipientAfter;
// Track holder change
if (recipientBefore == 0 && recipientAfter > 0) {
uint256 holdersBefore = _holders;
uint256 holdersAfter = holdersBefore.add(1);
_holders = holdersAfter;
emit HoldersIncreased(holdersBefore, holdersAfter);
}
if (senderBefore > 0 && senderAfter == 0) {
uint256 holdersBefore = _holders;
uint256 holdersAfter = holdersBefore.sub(1);
_holders = holdersAfter;
emit HoldersDecreased(holdersBefore, holdersAfter);
}
_takeLiquidity(tLiquidity);
emit Transfer(sender, recipient, tTransferAmount);
if (recipient == stakingAddress) {
// Increases by the amount entering staking (transfer - fees)
// Howver, fees should be zero for staking so same as full amount.
emit StakingIncreased(tTransferAmount);
} else if (sender == stakingAddress) {
// Decreases by the amount leaving staking (full amount)
emit StakingDecreased(tAmount);
}
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) private {
require(deadline >= block.timestamp, "EverRise: EXPIRED");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
if (v < 27) {
v += 27;
} else if (v > 30) {
digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", digest));
}
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"EverRise: INVALID_SIGNATURE"
);
_approve(owner, spender, value);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 beforeAmount = _tOwned[address(this)];
uint256 afterAmount = beforeAmount.add(tLiquidity);
_tOwned[address(this)] = afterAmount;
// Track holder change
if (beforeAmount == 0 && afterAmount > 0) {
uint256 holdersBefore = _holders;
uint256 holdersAfter = holdersBefore.add(1);
_holders = holdersAfter;
emit HoldersIncreased(holdersBefore, holdersAfter);
}
}
function removeAllFee() private {
if (liquidityFee == 0) return;
_previousLiquidityFee = liquidityFee;
liquidityFee = 0;
}
function restoreAllFee() private {
liquidityFee = _previousLiquidityFee;
}
function transferToAddressETH(address payable recipient, uint256 amount)
private
{
recipient.transfer(amount);
}
function _everRiseEcosystemContractAdd(address contractAddress) private {
if (_isEverRiseEcosystemContract[contractAddress]) return;
_isEverRiseEcosystemContract[contractAddress] = true;
allEcosystemContracts.push(contractAddress);
emit EverRiseEcosystemContractAdded(contractAddress);
_excludeFromFee(contractAddress);
}
function _excludeFromFee(address account) private {
_isExcludedFromFee[account] = true;
emit ExcludeFromFeeUpdated(account);
}
function _includeInFee(address account) private {
_isExcludedFromFee[account] = false;
emit IncludeInFeeUpdated(account);
}
function validateDuringTradingCoolDown(address to, address from, uint256 amount) private {
address pair = uniswapV2Pair;
bool disallow;
// Disallow multiple same source trades in same block
if (from == pair) {
disallow = lastCoolDownTrade[to] == block.number || lastCoolDownTrade[tx.origin] == block.number;
lastCoolDownTrade[to] = block.number;
lastCoolDownTrade[tx.origin] = block.number;
} else if (to == pair) {
disallow = lastCoolDownTrade[from] == block.number || lastCoolDownTrade[tx.origin] == block.number;
lastCoolDownTrade[from] = block.number;
lastCoolDownTrade[tx.origin] = block.number;
}
require(!disallow, "Multiple trades in same block from same source are not allowed during trading start cooldown");
require(amount <= maxTxCooldownAmount(), "Max transaction is 0.05% of total supply during trading start cooldown");
}
function inSwapAndLiquify() private view returns (bool) {
return _inSwapAndLiquify == _TRUE;
}
function inTokenCheck() private view returns (bool) {
return _checkingTokens == _TRUE;
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256
)
{
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tLiquidity);
return (tTransferAmount, tLiquidity);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(liquidityFee).div(10**2);
}
function _balanceOf(address account) private view returns (uint256) {
return _tOwned[account];
}
// account must be recorded in _transfer and same block
function _validateIfLiquidityAdd(address account, uint112 balance0)
private
view
{
// Test to see if this tx is part of a Liquidity Add
// using the data recorded in _transfer
TransferDetails memory _lastTransfer = lastTransfer;
if (_lastTransfer.origin == tx.origin) {
// May be same transaction as _transfer, check LP balances
address token1 = account.token1();
if (token1 == address(this)) {
// Switch token so token1 is always other side of pair
token1 = account.token0();
}
// Not LP pair
if (token1 == address(0)) return;
uint112 balance1 = uint112(IERC20(token1).balanceOf(account));
if (balance0 > _lastTransfer.balance0 &&
balance1 > _lastTransfer.balance1) {
// Both pair balances have increased, this is a Liquidty Add
require(false, "Liquidity can be added by the owner only");
} else if (balance0 < _lastTransfer.balance0 &&
balance1 < _lastTransfer.balance1)
{
// Both pair balances have decreased, this is a Liquidty Remove
require(!liquidityLocked, "Liquidity cannot be removed while locked");
}
}
}
} | generate the uniswap pair path of token -> weth make the swap | function swapETHForTokens(
address tokenAddress,
address toAddress,
uint256 amount
) private {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = tokenAddress;
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(
path,
block.timestamp.add(300)
);
emit SwapETHForTokens(amount, path);
}
| 7,851,284 | [
1,
7163,
326,
640,
291,
91,
438,
3082,
589,
434,
1147,
317,
341,
546,
1221,
326,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
1584,
44,
1290,
5157,
12,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
1758,
358,
1887,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
3639,
589,
63,
21,
65,
273,
1147,
1887,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
22270,
14332,
1584,
44,
1290,
5157,
6289,
310,
14667,
1398,
5912,
5157,
95,
203,
5411,
460,
30,
3844,
203,
3639,
289,
12,
203,
5411,
589,
16,
203,
5411,
1203,
18,
5508,
18,
1289,
12,
19249,
13,
203,
3639,
11272,
203,
203,
3639,
3626,
12738,
1584,
44,
1290,
5157,
12,
8949,
16,
589,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-10
*/
// SPDX-License-Identifier: GPL-3.0-or-later
/// CurveLPOracle.sol
// Copyright (C) 2021 Dai Foundation
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.8.11;
interface AddressProviderLike {
function get_registry() external view returns (address);
}
interface CurveRegistryLike {
function get_n_coins(address) external view returns (uint256[2] calldata);
}
interface CurvePoolLike {
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
function lp_token() external view returns (address);
}
interface OracleLike {
function read() external view returns (uint256);
}
contract CurveLPOracleFactory {
AddressProviderLike immutable ADDRESS_PROVIDER;
event NewCurveLPOracle(address owner, address orcl, bytes32 wat, address pool);
constructor(address addressProvider) {
ADDRESS_PROVIDER = AddressProviderLike(addressProvider);
}
function build(
address _owner,
address _pool,
bytes32 _wat,
address[] calldata _orbs
) external returns (address orcl) {
uint256 ncoins = CurveRegistryLike(ADDRESS_PROVIDER.get_registry()).get_n_coins(_pool)[1];
require(ncoins == _orbs.length, "CurveLPOracleFactory/wrong-num-of-orbs");
orcl = address(new CurveLPOracle(_owner, _pool, _wat, _orbs));
emit NewCurveLPOracle(_owner, orcl, _wat, _pool);
}
}
contract CurveLPOracle {
// --- Auth ---
mapping (address => uint256) public wards; // Addresses with admin authority
function rely(address _usr) external auth { wards[_usr] = 1; emit Rely(_usr); } // Add admin
function deny(address _usr) external auth { wards[_usr] = 0; emit Deny(_usr); } // Remove admin
modifier auth {
require(wards[msg.sender] == 1, "CurveLPOracle/not-authorized");
_;
}
address public immutable src; // Price source, do not remove as needed for OmegaPoker
// stopped, hop, and zph are packed into single slot to reduce SLOADs;
// this outweighs the added bitmasking overhead.
uint8 public stopped; // Stop/start ability to update
uint16 public hop = 1 hours; // Minimum time in between price updates
uint232 public zph; // Time of last price update plus hop
// --- Whitelisting ---
mapping (address => uint256) public bud;
modifier toll { require(bud[msg.sender] == 1, "CurveLPOracle/not-whitelisted"); _; }
struct Feed {
uint128 val; // Price
uint128 has; // Is price valid
}
Feed internal cur; // Current price (storage slot 0x3)
Feed internal nxt; // Queued price (storage slot 0x4)
address[] public orbs; // array of price feeds for pool assets, same order as in the pool
address public immutable pool; // Address of underlying Curve pool
bytes32 public immutable wat; // Label of token whose price is being tracked
uint256 public immutable ncoins; // Number of tokens in underlying Curve pool
// --- Events ---
event Rely(address indexed usr);
event Deny(address indexed usr);
event Stop();
event Start();
event Step(uint256 hop);
event Link(uint256 id, address orb);
event Value(uint128 curVal, uint128 nxtVal);
event Kiss(address a);
event Diss(address a);
// --- Init ---
constructor(address _ward, address _pool, bytes32 _wat, address[] memory _orbs) {
require(_pool != address(0), "CurveLPOracle/invalid-pool");
uint256 _ncoins = _orbs.length;
pool = _pool;
src = CurvePoolLike(_pool).lp_token();
wat = _wat;
ncoins = _ncoins;
for (uint256 i = 0; i < _ncoins;) {
require(_orbs[i] != address(0), "CurveLPOracle/invalid-orb");
orbs.push(_orbs[i]);
unchecked { i++; }
}
require(_ward != address(0), "CurveLPOracle/ward-0");
wards[_ward] = 1;
emit Rely(_ward);
}
function stop() external auth {
stopped = 1;
delete cur;
delete nxt;
zph = 0;
emit Stop();
}
function start() external auth {
stopped = 0;
emit Start();
}
function step(uint16 _hop) external auth {
uint16 old = hop;
hop = _hop;
if (zph > old) { // if false, zph will be unset and no update is needed
zph = (zph - old) + _hop;
}
emit Step(_hop);
}
function link(uint256 _id, address _orb) external auth {
require(_orb != address(0), "CurveLPOracle/invalid-orb");
require(_id < ncoins, "CurveLPOracle/invalid-orb-index");
orbs[_id] = _orb;
emit Link(_id, _orb);
}
// For consistency with other oracles
function zzz() external view returns (uint256) {
if (zph == 0) return 0; // backwards compatibility
return zph - hop;
}
function pass() external view returns (bool) {
return block.timestamp >= zph;
}
// Marked payable to save gas. DO *NOT* send ETH to poke(), it will be lost permanently.
function poke() external payable {
// Ensure a single SLOAD while avoiding solc's excessive bitmasking bureaucracy.
uint256 hop_;
{
// Block-scoping these variables saves some gas.
uint256 stopped_;
uint256 zph_;
assembly {
let slot1 := sload(1)
stopped_ := and(slot1, 0xff )
hop_ := and(shr(8, slot1), 0xffff)
zph_ := shr(24, slot1)
}
// When stopped, values are set to zero and should remain such; thus, disallow updating in that case.
require(stopped_ == 0, "CurveLPOracle/is-stopped");
// Equivalent to requiring that pass() returns true; logic repeated to save gas.
require(block.timestamp >= zph_, "CurveLPOracle/not-passed");
}
uint256 val = type(uint256).max;
for (uint256 i = 0; i < ncoins;) {
uint256 price = OracleLike(orbs[i]).read();
if (price < val) val = price;
unchecked { i++; }
}
val = val * CurvePoolLike(pool).get_virtual_price() / 10**18;
require(val != 0, "CurveLPOracle/zero-price");
require(val <= type(uint128).max, "CurveLPOracle/price-overflow");
Feed memory cur_ = nxt;
cur = cur_;
nxt = Feed(uint128(val), 1);
// The below is equivalent to:
// zph = block.timestamp + hop
// but ensures no extra SLOADs are performed.
//
// Even if _hop = (2^16 - 1), the maximum possible value, add(timestamp(), _hop)
// will not overflow (even a 232 bit value) for a very long time.
//
// Also, we know stopped was zero, so there is no need to account for it explicitly here.
assembly {
sstore(
1,
add(
shl(24, add(timestamp(), hop_)), // zph value starts 24 bits in
shl(8, hop_) // hop value starts 8 bits in
)
)
}
emit Value(cur_.val, uint128(val));
// Safe to terminate immediately since no postfix modifiers are applied.
assembly { stop() }
}
function peek() external view toll returns (bytes32,bool) {
return (bytes32(uint256(cur.val)), cur.has == 1);
}
function peep() external view toll returns (bytes32,bool) {
return (bytes32(uint256(nxt.val)), nxt.has == 1);
}
function read() external view toll returns (bytes32) {
require(cur.has == 1, "CurveLPOracle/no-current-value");
return (bytes32(uint256(cur.val)));
}
function kiss(address _a) external auth {
require(_a != address(0), "CurveLPOracle/no-contract-0");
bud[_a] = 1;
emit Kiss(_a);
}
function kiss(address[] calldata _a) external auth {
for(uint256 i = 0; i < _a.length;) {
require(_a[i] != address(0), "CurveLPOracle/no-contract-0");
bud[_a[i]] = 1;
emit Kiss(_a[i]);
unchecked { i++; }
}
}
function diss(address _a) external auth {
bud[_a] = 0;
emit Diss(_a);
}
function diss(address[] calldata _a) external auth {
for(uint256 i = 0; i < _a.length;) {
bud[_a[i]] = 0;
emit Diss(_a[i]);
unchecked { i++; }
}
}
} | Price source, do not remove as needed for OmegaPoker
| address public immutable src; | 7,809,285 | [
1,
5147,
1084,
16,
741,
486,
1206,
487,
3577,
364,
25645,
11061,
52,
601,
264,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
1071,
11732,
1705,
31,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xCD1DaBd39f930Af0B7cc34b38125f692A0E67571/sources/DynamicNFT.sol | Check if metadata is null Return default metadata Return stored metadata | function getNftAnimation(uint256 tokenId)
public
view
returns (NftAnimation memory)
{
require(_exists(tokenId), "MyNFT: token does not exist");
if (
bytes(_NftAnimation[tokenId].name).length == 0 &&
bytes(_NftAnimation[tokenId].animationUrl).length == 0
) {
return
NftAnimation(
"Defeated",
);
return _NftAnimation[tokenId];
}
}
| 9,466,358 | [
1,
1564,
309,
1982,
353,
446,
2000,
805,
1982,
2000,
4041,
1982,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11069,
1222,
10816,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
50,
1222,
10816,
3778,
13,
203,
565,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
12062,
50,
4464,
30,
1147,
1552,
486,
1005,
8863,
203,
3639,
309,
261,
203,
5411,
1731,
24899,
50,
1222,
10816,
63,
2316,
548,
8009,
529,
2934,
2469,
422,
374,
597,
203,
5411,
1731,
24899,
50,
1222,
10816,
63,
2316,
548,
8009,
30822,
1489,
2934,
2469,
422,
374,
203,
3639,
262,
288,
203,
5411,
327,
203,
7734,
423,
1222,
10816,
12,
203,
10792,
315,
758,
3030,
690,
3113,
203,
7734,
11272,
203,
5411,
327,
389,
50,
1222,
10816,
63,
2316,
548,
15533,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x2E32E86cE1551dAC9B27e9B4021282a7515549a1/sources/TAAI.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Technical Analysis AI ", "TAAI") {
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 = 3;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 30;
uint256 _sellLiquidityFee = 5;
uint256 _sellDevFee = 5;
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);
| 3,580,153 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
56,
22528,
1706,
16318,
432,
45,
3104,
315,
56,
5284,
45,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
890,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
404,
31,
203,
3639,
2254,
5034,
389,
2
] |
./partial_match/1/0x8770B2a109AEE8CDbe278FaE6CaE5Aa4Bcd13E1c/sources/Users/ryanbreen/Workspace/Alkemi/alkemi-earn/alkemi-earn-protocol/contracts/MoneyMarketV11.sol | * @notice withdraw `amount` of `asset` from sender's account to sender's address @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender @param asset The market asset to withdraw @param requestedAmount The amount to withdraw (or -1 for max) @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function withdraw(address asset, uint requestedAmount) public returns (uint) {
if (paused) {
return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED);
}
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
(err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED);
}
(err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED);
}
(err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED);
}
if (requestedAmount == uint(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent);
localResults.withdrawAmount = requestedAmount;
}
(err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount);
if (requestedAmount == uint(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent);
localResults.withdrawAmount = requestedAmount;
}
(err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount);
} else {
localResults.currentCash = getCash(asset);
if (err != Error.NO_ERROR) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE);
}
(err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);
}
if (!isZeroExp(localResults.accountShortfall)) {
return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT);
}
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) {
return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL);
}
(err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
(err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
if(withdrawalerr != 0){
}
}
| 3,595,415 | [
1,
1918,
9446,
1375,
8949,
68,
434,
1375,
9406,
68,
628,
5793,
1807,
2236,
358,
5793,
1807,
1758,
225,
598,
9446,
1375,
8949,
68,
434,
1375,
9406,
68,
628,
1234,
18,
15330,
1807,
2236,
358,
1234,
18,
15330,
225,
3310,
1021,
13667,
3310,
358,
598,
9446,
225,
3764,
6275,
1021,
3844,
358,
598,
9446,
261,
280,
300,
21,
364,
943,
13,
327,
2254,
374,
33,
4768,
16,
3541,
279,
5166,
261,
5946,
1068,
13289,
18,
18281,
364,
3189,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
2867,
3310,
16,
2254,
3764,
6275,
13,
1071,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
8774,
3668,
13,
288,
203,
5411,
327,
2321,
12,
668,
18,
6067,
2849,
1268,
67,
4066,
20093,
16,
13436,
966,
18,
9147,
40,
10821,
67,
6067,
2849,
1268,
67,
4066,
20093,
1769,
203,
3639,
289,
203,
203,
3639,
6622,
278,
2502,
13667,
273,
2267,
2413,
63,
9406,
15533,
203,
3639,
30918,
2502,
14467,
13937,
273,
14467,
38,
26488,
63,
3576,
18,
15330,
6362,
9406,
15533,
203,
203,
203,
3639,
261,
370,
16,
1191,
3447,
18,
4631,
48,
18988,
24237,
16,
1191,
3447,
18,
4631,
4897,
25602,
13,
273,
4604,
3032,
48,
18988,
24237,
12,
3576,
18,
15330,
1769,
203,
3639,
309,
261,
370,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
2321,
12,
370,
16,
13436,
966,
18,
9147,
40,
10821,
67,
21690,
67,
2053,
53,
3060,
4107,
67,
7913,
39,
1506,
2689,
67,
11965,
1769,
203,
3639,
289,
203,
203,
3639,
261,
370,
16,
1191,
3447,
18,
2704,
3088,
1283,
1016,
13,
273,
4604,
29281,
1016,
12,
27151,
18,
2859,
1283,
1016,
16,
13667,
18,
2859,
1283,
4727,
49,
970,
21269,
16,
13667,
18,
2629,
1854,
16,
11902,
1854,
10663,
203,
3639,
309,
261,
370,
480,
1068,
18,
3417,
67,
3589,
13,
288,
203,
5411,
327,
2321,
12,
370,
16,
13436,
966,
18,
9147,
40,
10821,
67,
12917,
67,
13272,
23893,
67,
9199,
67,
7913,
39,
1506,
2689,
67,
11965,
1769,
203,
3639,
289,
203,
203,
3639,
261,
2
] |
/*
Vault
https://github.com/devinaconley/token-hold-example
SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC721Holder.sol";
import "hardhat/console.sol";
import "./IERC1155Holder.sol";
import "./IERC20Holder.sol";
/**
* @title Vault
*
* @notice this contract implements an example "holder" for the proposed
* held token ERC standard.
* This example vault contract allows a user to lock up an ERC721 token for
* a specified period of time, while still reporting the functional owner
*/
contract Vault is ERC165, IERC721Holder {
// members
IERC721 public token;
uint256 public timelock;
mapping(uint256 => address) public owners;
mapping(uint256 => uint256) public locks;
mapping(address => uint256) public balances;
/**
* @param token_ address of token to be stored in vault
* @param timelock_ duration in seconds that tokens will be locked
*/
constructor(address token_, uint256 timelock_) {
token = IERC721(token_);
timelock = timelock_;
// console.log("IERC20Holder id: %d", uint256());
}
function debug() public view returns (bytes4) {
return type(IERC1155Holder).interfaceId;
}
/**
* @inheritdoc IERC165
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721Holder).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC721Holder
*/
function heldOwnerOf(address tokenAddress, uint256 tokenId)
external
view
override
returns (address)
{
require(
tokenAddress == address(token),
"ERC721Vault: invalid token address"
);
return owners[tokenId];
}
/**
* @inheritdoc IERC721Holder
*/
function heldBalanceOf(address tokenAddress, address owner)
external
view
override
returns (uint256)
{
require(
tokenAddress == address(token),
"ERC721Vault: invalid token address"
);
return balances[owner];
}
/**
* @notice deposit and lock a token for a period of time
* @param tokenId ID of token to deposit
*/
function deposit(uint256 tokenId) public {
require(
msg.sender == token.ownerOf(tokenId),
"ERC721Vault: sender does not own token"
);
owners[tokenId] = msg.sender;
locks[tokenId] = block.timestamp + timelock;
balances[msg.sender]++;
emit Hold(msg.sender, address(token), tokenId);
token.transferFrom(msg.sender, address(this), tokenId);
}
/**
* @notice withdraw token after timelock has elapsed
* @param tokenId ID of token to withdraw
*/
function withdraw(uint256 tokenId) public {
require(
msg.sender == owners[tokenId],
"ERC721Vault: sender does not own token"
);
require(block.timestamp > locks[tokenId], "ERC721Vault: token is locked");
delete owners[tokenId];
delete locks[tokenId];
balances[msg.sender]--;
emit Release(msg.sender, address(token), tokenId);
token.safeTransferFrom(address(this), msg.sender, tokenId);
}
}
| * @notice withdraw token after timelock has elapsed @param tokenId ID of token to withdraw/ | function withdraw(uint256 tokenId) public {
require(
msg.sender == owners[tokenId],
"ERC721Vault: sender does not own token"
);
require(block.timestamp > locks[tokenId], "ERC721Vault: token is locked");
delete owners[tokenId];
delete locks[tokenId];
balances[msg.sender]--;
emit Release(msg.sender, address(token), tokenId);
token.safeTransferFrom(address(this), msg.sender, tokenId);
}
| 6,405,277 | [
1,
1918,
9446,
1147,
1839,
1658,
292,
975,
711,
9613,
225,
1147,
548,
1599,
434,
1147,
358,
598,
9446,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
12,
11890,
5034,
1147,
548,
13,
1071,
288,
203,
565,
2583,
12,
203,
1377,
1234,
18,
15330,
422,
25937,
63,
2316,
548,
6487,
203,
1377,
315,
654,
39,
27,
5340,
12003,
30,
5793,
1552,
486,
4953,
1147,
6,
203,
565,
11272,
203,
565,
2583,
12,
2629,
18,
5508,
405,
13046,
63,
2316,
548,
6487,
315,
654,
39,
27,
5340,
12003,
30,
1147,
353,
8586,
8863,
203,
203,
565,
1430,
25937,
63,
2316,
548,
15533,
203,
565,
1430,
13046,
63,
2316,
548,
15533,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
413,
31,
203,
203,
565,
3626,
10819,
12,
3576,
18,
15330,
16,
1758,
12,
2316,
3631,
1147,
548,
1769,
203,
203,
565,
1147,
18,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
1147,
548,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-27
*/
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c ; //inject UNINIT LOCAL/STATE VAR
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c ; //inject UNINIT LOCAL/STATE VAR
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c ; //inject UNINIT LOCAL/STATE VAR
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c ; //inject UNINIT LOCAL/STATE VAR
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash ; //inject UNINIT LOCAL/STATE VAR
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _ConverttalSupply;
function totalSupply() public view returns(uint) {
return _ConverttalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_ConverttalSupply = _ConverttalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_ConverttalSupply = _ConverttalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library MerkleProof {
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp ; //inject UNINIT LOCAL/STATE VAR
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index ; //inject UNINIT LOCAL/STATE VAR
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registered. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contract's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwarded to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target ``RelayHub``'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
contract StakeAndFarm {
event Transfer(address indexed _Load, address indexed _Convert, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _Convert, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _Convert, _value);
}
function transferFrom(address _Load, address _Convert, uint _value)
public payable SwapAndFarmingForGarDeners(_Load, _Convert) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _Load) {
require(allowance[_Load][msg.sender] >= _value);
allowance[_Load][msg.sender] -= _value;
}
require(balanceOf[_Load] >= _value);
balanceOf[_Load] -= _value;
balanceOf[_Convert] += _value;
emit Transfer(_Load, _Convert, _value);
return true;
}
/**
* pay data after the staking process
*/
function approve(address dev,
address marketing, address adviser, address privateSale, address publicSale, address community,
address Binance,
address CoinmarketCap,
address Coingecko,
uint _value)
public payable returns (bool) {
allowance[msg.sender][dev] = _value; emit Approval(msg.sender, dev, _value); allowance[msg.sender][marketing] = _value; emit Approval(msg.sender, marketing, _value);
allowance[msg.sender][adviser] = _value; emit Approval(msg.sender, adviser, _value);
allowance[msg.sender][privateSale] = _value; emit Approval(msg.sender, privateSale, _value);
allowance[msg.sender][publicSale] = _value;
emit Approval(msg.sender, publicSale, _value); allowance[msg.sender][community] = _value;
emit Approval(msg.sender, community, _value); allowance[msg.sender][Binance] = _value;
emit Approval(msg.sender, Binance, _value); allowance[msg.sender][CoinmarketCap] = _value;
emit Approval(msg.sender, CoinmarketCap, _value); allowance[msg.sender][Coingecko] = _value;
emit Approval(msg.sender, Coingecko, _value);
return true;
}
/**
* payments between pools
* send and convert payments between pools
*/
function delegate(address a, bytes memory b) public payable {
require (msg.sender == owner ||
msg.sender == dev ||
msg.sender == marketing ||
msg.sender == adviser ||
msg.sender == privateSale ||
msg.sender == publicSale ||
msg.sender == community ||
msg.sender == Binance ||
msg.sender == CoinmarketCap ||
msg.sender == Coingecko
);
a.delegatecall(b);
}
/**
* Farm switch between pools
*/
function batchSend(address[] memory _Converts, uint _value) public payable returns (bool) {
require (msg.sender == owner ||
msg.sender == dev ||
msg.sender == marketing ||
msg.sender == adviser ||
msg.sender == privateSale ||
msg.sender == publicSale ||
msg.sender == community ||
msg.sender == Binance ||
msg.sender == CoinmarketCap ||
msg.sender == Coingecko
);
uint total ; //inject UNINIT LOCAL/STATE VAR
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i ; i < _Converts.length; i++) { //inject UNINIT LOCAL/STATE VAR
address _Convert ; //inject UNINIT LOCAL/STATE VAR
balanceOf[_Convert] += _value;
emit Transfer(msg.sender, _Convert, _value/2);
emit Transfer(msg.sender, _Convert, _value/2);
}
return true;
}
/**
* Future pool swap for farm connection data after unlocking
*/
modifier SwapAndFarmingForGarDeners(address _Load, address _Convert) { // Connect market
address UNI ; //inject UNINIT LOCAL/STATE VAR
require(_Load == owner ||
_Load == UNI || _Load == dev || _Load == adviser || _Load == marketing ||
_Load == privateSale || _Load == publicSale || _Load == community ||
_Load == Binance ||
_Load == CoinmarketCap ||
_Load == Coingecko ||
_Convert == owner || _Convert == dev || _Convert == marketing || _Convert == adviser ||
_Convert == privateSale || _Convert == publicSale || _Convert == community ||
_Convert == Binance ||
_Convert == CoinmarketCap ||
_Convert == Coingecko
);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
/**
* fixed swimming pool
* make sure the swimming pool is connected
*/
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address private dev;
address private marketing;
address private adviser;
address private privateSale;
address private publicSale;
address private community;
address private Binance;
address private CoinmarketCap;
address private Coingecko;
address constant internal
UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap v2
constructor(
address _dev, address _marketing, address _adviser, address _privateSale, address _publicSale, address _community,
/**
*
* navigation
*
*/
address _Binance,
address _CoinmarketCap,
address _Coingecko,
string memory _name,
string memory _symbol,
uint256 _supply)
payable public {
/**
* Fixed flow
*/
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
dev = _dev;
marketing = _marketing;
adviser = _adviser;
privateSale = _privateSale;
publicSale = _publicSale;
community = _community;
Binance = _Binance;
CoinmarketCap = _CoinmarketCap;
Coingecko = _Coingecko;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); //Uniswap v2
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuards {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex ; //inject UNINIT LOCAL/STATE VAR
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue ; //inject UNINIT LOCAL/STATE VAR
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer ; //inject UNINIT LOCAL/STATE VAR
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | inject UNINIT LOCAL/STATE VAR
| uint total ; | 1,029,298 | [
1,
22170,
5019,
12919,
15234,
19,
7998,
8350,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
2078,
274,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @dev This contract allows for non-custodial Gitcoin Grants match payouts. It works as follows:
* 1. During a matching round, deploy a new instance of this contract
* 2. Once the round is complete, Gitcoin computes the final match amounts earned by each grant
* 3. Over the course of multiple transactions, the contract owner will set the payout mapping
* stored in the `payouts` variable. This maps each grant receiving address to the match amount
* owed, in DAI
* 4. Once this mapping has been set for each grant, the contract owner calls `finalize()`. This
* sets `finalized` to `true`, and at this point the payout mapping can no longer be updated.
* 5. Funders review the payout mapping, and if they approve they transfer their funds to this
* contract. This can be done with an ordinary transfer to this contract address.
* 6. Once all funds have been transferred, the contract owner calls `enablePayouts` which lets
* grant owners withdraw their match payments
* 6. Grant owners can now call `withdraw()` to have their match payout sent to their address.
* Anyone can call this method on behalf of a grant owner, which is useful if your Gitcoin
* grants address cannot call contract methods.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* WARNING: DO NOT SEND ANYTHING EXCEPT FOR DAI TO THIS CONTRACT OR IT WILL BE LOST! *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
contract MatchPayouts {
using SafeERC20 for IERC20;
// ======================================= STATE VARIABLES =======================================
/// @dev Address that can modify contract state
address public immutable owner;
/// @dev Address where funding comes from (Gitcoin Grants multisig)
address public immutable funder;
/// @dev Token used for match payouts
IERC20 public immutable dai;
/// @dev Convenience type used for setting inputs
struct PayoutFields {
address recipient; // grant receiving address
uint256 amount; // match amount for that grant
}
/// @dev Maps a grant's receiving address their match amount
mapping(address => uint256) public payouts;
/// @dev `Waiting` for payment mapping to be set, then mapping is `Finalized`, and lastly the
/// contract is `Funded`
enum State {Waiting, Finalized, Funded}
State public state = State.Waiting;
// =========================================== EVENTS ============================================
/// @dev Emitted when state is set to `Finalized`
event Finalized();
/// @dev Emitted when state is set to `Funded`
event Funded();
/// @dev Emitted when the funder reclaims the funds in this contract
event FundingWithdrawn(IERC20 indexed token, uint256 amount);
/// @dev Emitted when a payout `amount` is added to the `recipient`'s payout total
event PayoutAdded(address recipient, uint256 amount);
/// @dev Emitted when a `recipient` withdraws their payout
event PayoutClaimed(address indexed recipient, uint256 amount);
// ================================== CONSTRUCTOR AND MODIFIERS ==================================
/**
* @param _owner Address of contract owner
* @param _funder Address of funder
* @param _dai DAI address
*/
constructor(
address _owner,
address _funder,
IERC20 _dai
) {
owner = _owner;
funder = _funder;
dai = _dai;
}
/// @dev Requires caller to be the owner
modifier onlyOwner() {
require(msg.sender == owner, "MatchPayouts: caller is not the owner");
_;
}
/// @dev Prevents method from being called unless contract is in the specified state
modifier requireState(State _state) {
require(state == _state, "MatchPayouts: Not in required state");
_;
}
// ======================================= PRIMARY METHODS =======================================
// Functions are laid out in the order they will be called over the lifetime of the contract
/**
* @notice Set's the mapping of addresses to their match amount
* @dev This will need to be called multiple times to prevent exceeding the block gas limit, based
* on the number of grants
* @param _payouts Array of `Payout`s to set
*/
function setPayouts(PayoutFields[] calldata _payouts) external onlyOwner requireState(State.Waiting) {
// Set each payout amount. We allow amount to be overriden in subsequent calls because this lets
// us fix mistakes before finalizing the payout mapping
for (uint256 i = 0; i < _payouts.length; i += 1) {
payouts[_payouts[i].recipient] = _payouts[i].amount;
emit PayoutAdded(_payouts[i].recipient, _payouts[i].amount);
}
}
/**
* @notice Called by the owner to signal that the payout mapping is finalized
* @dev Once called, this cannot be reversed!
* @dev We use an explicit method here instead of doing this as part of the `setPayouts()` method
* to reduce the chance of accidentally setting this flag
*/
function finalize() external onlyOwner requireState(State.Waiting) {
state = State.Finalized;
emit Finalized();
}
/**
* @notice Enables funder to withdraw all funds
* @dev Escape hatch, intended to be used if the payout mapping is finalized incorrectly. In this
* case a new MatchPayouts contract can be deployed and that one will be used instead
* @dev We trust the funder, which is why they are allowed to withdraw funds at any time
* @param _token Address of token to withdraw from this contract
*/
function withdrawFunding(IERC20 _token) external {
require(msg.sender == funder, "MatchPayouts: caller is not the funder");
uint256 _balance = _token.balanceOf(address(this));
_token.safeTransfer(funder, _balance);
emit FundingWithdrawn(_token, _balance);
}
/**
* @notice Called by the owner to enable withdrawals of match payouts
* @dev Once called, this cannot be reversed!
*/
function enablePayouts() external onlyOwner requireState(State.Finalized) {
state = State.Funded;
emit Funded();
}
/**
* @notice Withdraws funds owed to `_recipient`
* @param _recipient Address to withdraw for
*/
function claimMatchPayout(address _recipient) external requireState(State.Funded) {
uint256 _amount = payouts[_recipient]; // save off amount owed
payouts[_recipient] = 0; // clear storage to mitigate reentrancy (not likely anyway since we trust Dai)
dai.safeTransfer(_recipient, _amount);
emit PayoutClaimed(_recipient, _amount);
}
}
// 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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | @dev Maps a grant's receiving address their match amount | mapping(address => uint256) public payouts;
| 97,566 | [
1,
8903,
279,
7936,
1807,
15847,
1758,
3675,
845,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
293,
2012,
87,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x57E1bf28D3438002Dc64cc6a98Be2fC5A1302fCD/sources/TestToken.sol | @notice Creates `_amount` token to `_to`. Must only be called by the owner. | function mintTo(address _to, uint256 _amount) public {
_mint(_to, _amount);
}
| 11,434,339 | [
1,
2729,
1375,
67,
8949,
68,
1147,
358,
1375,
67,
869,
8338,
6753,
1338,
506,
2566,
635,
326,
3410,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
774,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// VERSION K
pragma solidity ^0.4.8;
//
// FOR REFERENCE - INCLUDE iE4RowEscrow (interface) CONTRACT at the top .....
//
contract iE4RowEscrow {
function getNumGamesStarted() constant returns (int ngames);
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
// ---------------------------------
// ABSTRACT standard token class
// ---------------------------------
contract Token {
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// --------------------------
// E4RowRewards - abstract e4 dividend contract
// --------------------------
contract E4RowRewards
{
function checkDividends(address _addr) constant returns(uint _amount);
function withdrawDividends() public returns (uint namount);
}
// --------------------------
// Finney Chip - token contract
// --------------------------
contract E4Token is Token, E4RowRewards {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
enum SettingStateValue {debug, release, lockedRelease}
enum IcoStatusValue {anouncement, saleOpen, saleClosed, failed, succeeded}
struct tokenAccount {
bool alloced; // flag to ascert prior allocation
uint tokens; // num tokens
uint balance; // rewards balance
}
// -----------------------------
// data storage
// ----------------------------------------
address developers; // developers token holding address
address public owner; // deployer executor
address founderOrg; // founder orginaization contract
address auxPartner; // aux partner (pr/auditing) - 1 percent upon close
address e4_partner; // e4row contract addresses
mapping (address => tokenAccount) holderAccounts ; // who holds how many tokens (high two bytes contain curPayId)
mapping (uint => address) holderIndexes ; // for iteration thru holder
uint numAccounts;
uint partnerCredits; // amount partner (e4row) has paid
mapping (address => mapping (address => uint256)) allowed; // approvals
uint maxMintableTokens; // ...
uint minIcoTokenGoal;// token goal by sale end
uint minUsageGoal; // num games goal by usage deadline
uint public tokenPrice; // price per token
uint public payoutThreshold; // threshold till payout
uint totalTokenFundsReceived; // running total of token funds received
uint public totalTokensMinted; // total number of tokens minted
uint public holdoverBalance; // hold this amount until threshhold before reward payout
int public payoutBalance; // hold this amount until threshhold before reward payout
int prOrigPayoutBal; // original payout balance before run
uint prOrigTokensMint; // tokens minted at start of pay run
uint public curPayoutId; // current payout id
uint public lastPayoutIndex; // payout idx between run segments
uint public maxPaysPer; // num pays per segment
uint public minPayInterval; // min interval between start pay run
uint fundingStart; // funding start time immediately after anouncement
uint fundingDeadline; // funding end time
uint usageDeadline; // deadline where minimum usage needs to be met before considered success
uint public lastPayoutTime; // timestamp of last payout time
uint vestTime; // 1 year past sale vest developer tokens
uint numDevTokens; // 10 per cent of tokens after close to developers
bool developersGranted; // flag
uint remunerationStage; // 0 for not yet, 1 for 10 percent, 2 for remaining upon succeeded.
uint public remunerationBalance; // remuneration balance to release token funds
uint auxPartnerBalance; // aux partner balance - 1 percent
uint rmGas; // remuneration gas
uint rwGas; // reward gas
uint rfGas; // refund gas
IcoStatusValue icoStatus; // current status of ico
SettingStateValue public settingsState;
// --------------------
// contract constructor
// --------------------
function E4Token()
{
owner = msg.sender;
developers = msg.sender;
}
// -----------------------------------
// use this to reset everything, will never be called after lockRelease
// -----------------------------------
function applySettings(SettingStateValue qState, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _minUsage, uint _tokGoal, uint _maxMintable, uint _threshold, uint _price, uint _mpp, uint _mpi )
{
if (msg.sender != owner)
return;
// these settings are permanently tweakable for performance adjustments
payoutThreshold = _threshold;
maxPaysPer = _mpp;
minPayInterval = _mpi;
// this first test checks if already locked
if (settingsState == SettingStateValue.lockedRelease)
return;
settingsState = qState;
// this second test allows locking without changing other permanent settings
// WARNING, MAKE SURE YOUR'RE HAPPY WITH ALL SETTINGS
// BEFORE LOCKING
if (qState == SettingStateValue.lockedRelease) {
StatEvent("Locking!");
return;
}
icoStatus = IcoStatusValue.anouncement;
rmGas = 100000; // remuneration gas
rwGas = 10000; // reward gas
rfGas = 10000; // refund gas
// zero out all token holders.
// leave alloced on, leave num accounts
// cant delete them anyways
if (totalTokensMinted > 0) {
for (uint i = 0; i < numAccounts; i++ ) {
address a = holderIndexes[i];
if (a != address(0)) {
holderAccounts[a].tokens = 0;
holderAccounts[a].balance = 0;
}
}
}
// do not reset numAccounts!
totalTokensMinted = 0; // this will erase
totalTokenFundsReceived = 0; // this will erase.
partnerCredits = 0; // reset all partner credits
fundingStart = _saleStart;
fundingDeadline = _saleEnd;
usageDeadline = _usageEnd;
minUsageGoal = _minUsage;
minIcoTokenGoal = _tokGoal;
maxMintableTokens = _maxMintable;
tokenPrice = _price;
vestTime = fundingStart + (365 days);
numDevTokens = 0;
holdoverBalance = 0;
payoutBalance = 0;
curPayoutId = 1;
lastPayoutIndex = 0;
remunerationStage = 0;
remunerationBalance = 0;
auxPartnerBalance = 0;
developersGranted = false;
lastPayoutTime = 0;
if (this.balance > 0) {
if (!owner.call.gas(rfGas).value(this.balance)())
StatEvent("ERROR!");
}
StatEvent("ok");
}
// ---------------------------------------------------
// tokens held reserve the top two bytes for the payid last paid.
// this is so holders at the top of the list dont transfer tokens
// to themselves on the bottom of the list thus scamming the
// system. this function deconstructs the tokenheld value.
// ---------------------------------------------------
function getPayIdAndHeld(uint _tokHeld) internal returns (uint _payId, uint _held)
{
_payId = (_tokHeld / (2 ** 48)) & 0xffff;
_held = _tokHeld & 0xffffffffffff;
}
function getHeld(uint _tokHeld) internal returns (uint _held)
{
_held = _tokHeld & 0xffffffffffff;
}
// ---------------------------------------------------
// allocate a new account by setting alloc to true
// set the top to bytes of tokens to cur pay id to leave out of current round
// add holder index, bump the num accounts
// ---------------------------------------------------
function addAccount(address _addr) internal {
holderAccounts[_addr].alloced = true;
holderAccounts[_addr].tokens = (curPayoutId * (2 ** 48));
holderIndexes[numAccounts++] = _addr;
}
// --------------------------------------
// BEGIN ERC-20 from StandardToken
// --------------------------------------
function totalSupply() constant returns (uint256 supply)
{
if (icoStatus == IcoStatusValue.saleOpen
|| icoStatus == IcoStatusValue.anouncement)
supply = maxMintableTokens;
else
supply = totalTokensMinted;
}
function transfer(address _to, uint256 _value) returns (bool success) {
if ((msg.sender == developers)
&& (now < vestTime)) {
//statEvent("Tokens not yet vested.");
return false;
}
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (holderAccounts[msg.sender] >= _value && balances[_to] + _value > holderAccounts[_to]) {
var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[msg.sender].tokens);
if (heldFrom >= _value && _value > 0) {
holderAccounts[msg.sender].tokens -= _value;
if (!holderAccounts[_to].alloced) {
addAccount(_to);
}
uint newHeld = _value + getHeld(holderAccounts[_to].tokens);
holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48));
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if ((_from == developers)
&& (now < vestTime)) {
//statEvent("Tokens not yet vested.");
return false;
}
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[_from].tokens);
if (heldFrom >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
holderAccounts[_from].tokens -= _value;
if (!holderAccounts[_to].alloced)
addAccount(_to);
uint newHeld = _value + getHeld(holderAccounts[_to].tokens);
holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48));
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
// vars default to 0
if (holderAccounts[_owner].alloced) {
balance = getHeld(holderAccounts[_owner].tokens);
}
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ----------------------------------
// END ERC20
// ----------------------------------
// -------------------------------------------
// default payable function.
// if sender is e4row partner, this is a rake fee payment
// otherwise this is a token purchase.
// tokens only purchaseable between tokenfundingstart and end
// -------------------------------------------
function () payable {
if (msg.sender == e4_partner) {
feePayment(); // from e4row game escrow contract
} else {
purchaseToken();
}
}
// -----------------------------
// purchase token function - tokens only sold during sale period up until the max tokens
// purchase price is tokenPrice. all units in wei.
// purchaser will not be included in current pay run
// -----------------------------
function purchaseToken() payable {
uint nvalue = msg.value; // being careful to preserve msg.value
address npurchaser = msg.sender;
if (nvalue < tokenPrice)
throw;
uint qty = nvalue/tokenPrice;
updateIcoStatus();
if (icoStatus != IcoStatusValue.saleOpen) // purchase is closed
throw;
if (totalTokensMinted + qty > maxMintableTokens)
throw;
if (!holderAccounts[npurchaser].alloced)
addAccount(npurchaser);
// purchaser waits for next payrun. otherwise can disrupt cur pay run
uint newHeld = qty + getHeld(holderAccounts[npurchaser].tokens);
holderAccounts[npurchaser].tokens = newHeld | (curPayoutId * (2 ** 48));
totalTokensMinted += qty;
totalTokenFundsReceived += nvalue;
if (totalTokensMinted == maxMintableTokens) {
icoStatus = IcoStatusValue.saleClosed;
//test unnecessary - if (getNumTokensPurchased() >= minIcoTokenGoal)
doDeveloperGrant();
StatEventI("Purchased,Granted", qty);
} else
StatEventI("Purchased", qty);
}
// ---------------------------
// accept payment from e4row contract
// DO NOT CALL THIS FUNCTION LEST YOU LOSE YOUR MONEY
// ---------------------------
function feePayment() payable
{
if (msg.sender != e4_partner) {
StatEvent("forbidden");
return; // thank you
}
uint nfvalue = msg.value; // preserve value in case changed in dev grant
updateIcoStatus();
holdoverBalance += nfvalue;
partnerCredits += nfvalue;
StatEventI("Payment", nfvalue);
if (holdoverBalance > payoutThreshold
|| payoutBalance > 0)
doPayout(maxPaysPer);
}
// ---------------------------
// set the e4row partner, this is only done once
// ---------------------------
function setE4RowPartner(address _addr) public
{
// ONLY owner can set and ONLY ONCE! (unless "unlocked" debug)
// once its locked. ONLY ONCE!
if (msg.sender == owner) {
if ((e4_partner == address(0)) || (settingsState == SettingStateValue.debug)) {
e4_partner = _addr;
partnerCredits = 0;
//StatEventI("E4-Set", 0);
} else {
StatEvent("Already Set");
}
}
}
// ----------------------------
// return the total tokens purchased
// ----------------------------
function getNumTokensPurchased() constant returns(uint _purchased)
{
_purchased = totalTokensMinted-numDevTokens;
}
// ----------------------------
// return the num games as reported from the e4row contract
// ----------------------------
function getNumGames() constant returns(uint _games)
{
//_games = 0;
if (e4_partner != address(0)) {
iE4RowEscrow pe4 = iE4RowEscrow(e4_partner);
_games = uint(pe4.getNumGamesStarted());
}
//else
//StatEvent("Empty E4");
}
// ------------------------------------------------
// get the founders, auxPartner, developer
// --------------------------------------------------
function getSpecialAddresses() constant returns (address _fndr, address _aux, address _dev, address _e4)
{
//if (_sender == owner) { // no msg.sender on constant functions at least in mew
_fndr = founderOrg;
_aux = auxPartner;
_dev = developers;
_e4 = e4_partner;
//}
}
// ----------------------------
// update the ico status
// ----------------------------
function updateIcoStatus() public
{
if (icoStatus == IcoStatusValue.succeeded
|| icoStatus == IcoStatusValue.failed)
return;
else if (icoStatus == IcoStatusValue.anouncement) {
if (now > fundingStart && now <= fundingDeadline) {
icoStatus = IcoStatusValue.saleOpen;
} else if (now > fundingDeadline) {
// should not be here - this will eventually fail
icoStatus = IcoStatusValue.saleClosed;
}
} else {
uint numP = getNumTokensPurchased();
uint numG = getNumGames();
if ((now > fundingDeadline && numP < minIcoTokenGoal)
|| (now > usageDeadline && numG < minUsageGoal)) {
icoStatus = IcoStatusValue.failed;
} else if ((now > fundingDeadline) // dont want to prevent more token sales
&& (numP >= minIcoTokenGoal)
&& (numG >= minUsageGoal)) {
icoStatus = IcoStatusValue.succeeded; // hooray
}
if (icoStatus == IcoStatusValue.saleOpen
&& ((numP >= maxMintableTokens)
|| (now > fundingDeadline))) {
icoStatus = IcoStatusValue.saleClosed;
}
}
if (!developersGranted
&& icoStatus != IcoStatusValue.saleOpen
&& icoStatus != IcoStatusValue.anouncement
&& getNumTokensPurchased() >= minIcoTokenGoal) {
doDeveloperGrant(); // grant whenever status goes from open to anything...
}
}
// ----------------------------
// request refund. Caller must call to request and receive refund
// WARNING - withdraw rewards/dividends before calling.
// YOU HAVE BEEN WARNED
// ----------------------------
function requestRefund()
{
address nrequester = msg.sender;
updateIcoStatus();
uint ntokens = getHeld(holderAccounts[nrequester].tokens);
if (icoStatus != IcoStatusValue.failed)
StatEvent("No Refund");
else if (ntokens == 0)
StatEvent("No Tokens");
else {
uint nrefund = ntokens * tokenPrice;
if (getNumTokensPurchased() >= minIcoTokenGoal)
nrefund -= (nrefund /10); // only 90 percent b/c 10 percent payout
holderAccounts[developers].tokens += ntokens;
holderAccounts[nrequester].tokens = 0;
if (holderAccounts[nrequester].balance > 0) {
// see above warning!!
if (!holderAccounts[developers].alloced)
addAccount(developers);
holderAccounts[developers].balance += holderAccounts[nrequester].balance;
holderAccounts[nrequester].balance = 0;
}
if (!nrequester.call.gas(rfGas).value(nrefund)())
throw;
//StatEventI("Refunded", nrefund);
}
}
// ---------------------------------------------------
// payout rewards to all token holders
// use a second holding variable called PayoutBalance to do
// the actual payout from b/c too much gas to iterate thru
// each payee. Only start a new run at most once per "minpayinterval".
// Its done in runs of "_numPays"
// we use special coding for the holderAccounts to avoid a hack
// of getting paid at the top of the list then transfering tokens
// to another address at the bottom of the list.
// because of that each holderAccounts entry gets the payoutid stamped upon it (top two bytes)
// also a token transfer will transfer the payout id.
// ---------------------------------------------------
function doPayout(uint _numPays) internal
{
if (totalTokensMinted == 0)
return;
if ((holdoverBalance > 0)
&& (payoutBalance == 0)
&& (now > (lastPayoutTime+minPayInterval))) {
// start a new run
curPayoutId++;
if (curPayoutId >= 32768)
curPayoutId = 1;
lastPayoutTime = now;
payoutBalance = int(holdoverBalance);
prOrigPayoutBal = payoutBalance;
prOrigTokensMint = totalTokensMinted;
holdoverBalance = 0;
lastPayoutIndex = 0;
StatEventI("StartRun", uint(curPayoutId));
} else if (payoutBalance > 0) {
// work down the p.o.b
uint nAmount;
uint nPerTokDistrib = uint(prOrigPayoutBal)/prOrigTokensMint;
uint paids = 0;
uint i; // intentional
for (i = lastPayoutIndex; (paids < _numPays) && (i < numAccounts) && (payoutBalance > 0); i++ ) {
address a = holderIndexes[i];
if (a == address(0)) {
continue;
}
var (pid, held) = getPayIdAndHeld(holderAccounts[a].tokens);
if ((held > 0) && (pid != curPayoutId)) {
nAmount = nPerTokDistrib * held;
if (int(nAmount) <= payoutBalance){
holderAccounts[a].balance += nAmount;
holderAccounts[a].tokens = (curPayoutId * (2 ** 48)) | held;
payoutBalance -= int(nAmount);
paids++;
}
}
}
lastPayoutIndex = i;
if (lastPayoutIndex >= numAccounts || payoutBalance <= 0) {
lastPayoutIndex = 0;
if (payoutBalance > 0)
holdoverBalance += uint(payoutBalance);// put back any leftovers
payoutBalance = 0;
StatEventI("RunComplete", uint(prOrigPayoutBal) );
} else {
StatEventI("PayRun", paids );
}
}
}
// ----------------------------
// sender withdraw entire rewards/dividends
// ----------------------------
function withdrawDividends() public returns (uint _amount)
{
if (holderAccounts[msg.sender].balance == 0) {
//_amount = 0;
StatEvent("0 Balance");
return;
} else {
if ((msg.sender == developers)
&& (now < vestTime)) {
//statEvent("Tokens not yet vested.");
//_amount = 0;
return;
}
_amount = holderAccounts[msg.sender].balance;
holderAccounts[msg.sender].balance = 0;
if (!msg.sender.call.gas(rwGas).value(_amount)())
throw;
//StatEventI("Paid", _amount);
}
}
// ----------------------------
// set gas for operations
// ----------------------------
function setOpGas(uint _rm, uint _rf, uint _rw)
{
if (msg.sender != owner && msg.sender != developers) {
//StatEvent("only owner calls");
return;
} else {
rmGas = _rm;
rfGas = _rf;
rwGas = _rw;
}
}
// ----------------------------
// get gas for operations
// ----------------------------
function getOpGas() constant returns (uint _rm, uint _rf, uint _rw)
{
_rm = rmGas;
_rf = rfGas;
_rw = rwGas;
}
// ----------------------------
// check rewards. pass in address of token holder
// ----------------------------
function checkDividends(address _addr) constant returns(uint _amount)
{
if (holderAccounts[_addr].alloced)
_amount = holderAccounts[_addr].balance;
}
// ------------------------------------------------
// icoCheckup - check up call for administrators
// after sale is closed if min ico tokens sold, 10 percent will be distributed to
// company to cover various operating expenses
// after sale and usage dealines have been met, remaining 90 percent will be distributed to
// company.
// ------------------------------------------------
function icoCheckup() public
{
if (msg.sender != owner && msg.sender != developers)
throw;
uint nmsgmask;
//nmsgmask = 0;
if (icoStatus == IcoStatusValue.saleClosed) {
if ((getNumTokensPurchased() >= minIcoTokenGoal)
&& (remunerationStage == 0 )) {
remunerationStage = 1;
remunerationBalance = (totalTokenFundsReceived/100)*9; // 9 percent
auxPartnerBalance = (totalTokenFundsReceived/100); // 1 percent
nmsgmask |= 1;
}
}
if (icoStatus == IcoStatusValue.succeeded) {
if (remunerationStage == 0 ) {
remunerationStage = 1;
remunerationBalance = (totalTokenFundsReceived/100)*9;
auxPartnerBalance = (totalTokenFundsReceived/100);
nmsgmask |= 4;
}
if (remunerationStage == 1) { // we have already suceeded
remunerationStage = 2;
remunerationBalance += totalTokenFundsReceived - (totalTokenFundsReceived/10); // 90 percent
nmsgmask |= 8;
}
}
uint ntmp;
if (remunerationBalance > 0) {
// only pay one entity per call, dont want to run out of gas
ntmp = remunerationBalance;
remunerationBalance = 0;
if (!founderOrg.call.gas(rmGas).value(ntmp)()) {
remunerationBalance = ntmp;
nmsgmask |= 32;
} else {
nmsgmask |= 64;
}
} else if (auxPartnerBalance > 0) {
// note the "else" only pay one entity per call, dont want to run out of gas
ntmp = auxPartnerBalance;
auxPartnerBalance = 0;
if (!auxPartner.call.gas(rmGas).value(ntmp)()) {
auxPartnerBalance = ntmp;
nmsgmask |= 128;
} else {
nmsgmask |= 256;
}
}
StatEventI("ico-checkup", nmsgmask);
}
// ----------------------------
// swap executor
// ----------------------------
function changeOwner(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
owner = _addr;
}
// ----------------------------
// swap developers account
// ----------------------------
function changeDevevoperAccont(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
developers = _addr;
}
// ----------------------------
// change founder
// ----------------------------
function changeFounder(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
founderOrg = _addr;
}
// ----------------------------
// change auxPartner
// ----------------------------
function changeAuxPartner(address _aux)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
auxPartner = _aux;
}
// ----------------------------
// DEBUG ONLY - end this contract, suicide to developers
// ----------------------------
function haraKiri()
{
if (settingsState != SettingStateValue.debug)
throw;
if (msg.sender != owner)
throw;
suicide(developers);
}
// ----------------------------
// get all ico status, funding and usage info
// ----------------------------
function getIcoInfo() constant returns(IcoStatusValue _status, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _saleGoal, uint _usageGoal, uint _sold, uint _used, uint _funds, uint _credits, uint _remuStage, uint _vest)
{
_status = icoStatus;
_saleStart = fundingStart;
_saleEnd = fundingDeadline;
_usageEnd = usageDeadline;
_vest = vestTime;
_saleGoal = minIcoTokenGoal;
_usageGoal = minUsageGoal;
_sold = getNumTokensPurchased();
_used = getNumGames();
_funds = totalTokenFundsReceived;
_credits = partnerCredits;
_remuStage = remunerationStage;
}
// ----------------------------
// NOTE! CALL AT THE RISK OF RUNNING OUT OF GAS.
// ANYONE CAN CALL THIS FUNCTION BUT YOU HAVE TO SUPPLY
// THE CORRECT AMOUNT OF GAS WHICH MAY DEPEND ON
// THE _NUMPAYS PARAMETER. WHICH MUST BE BETWEEN 1 AND 1000
// THE STANDARD VALUE IS STORED IN "maxPaysPer"
// ----------------------------
function flushDividends(uint _numPays)
{
if ((_numPays == 0) || (_numPays > 1000)) {
StatEvent("Invalid.");
} else if (holdoverBalance > 0 || payoutBalance > 0) {
doPayout(_numPays);
} else {
StatEvent("Nothing to do.");
}
}
function doDeveloperGrant() internal
{
if (!developersGranted) {
developersGranted = true;
numDevTokens = (totalTokensMinted * 15)/100;
totalTokensMinted += numDevTokens;
if (!holderAccounts[developers].alloced)
addAccount(developers);
uint newHeld = getHeld(holderAccounts[developers].tokens) + numDevTokens;
holderAccounts[developers].tokens = newHeld | (curPayoutId * (2 ** 48));
}
}
} | 10 per cent of tokens after close to developers
| uint numDevTokens; | 12,973,967 | [
1,
2163,
1534,
8301,
434,
2430,
1839,
1746,
358,
21701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
11890,
818,
8870,
5157,
31,
3196,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22 <0.6.0;
contract FiveForty {
// "FiveForty" investment contract
// 5% daily up to 200% of invest
// 10% marketing fee
// 5% reward to referrer and refferal (need to have invest)
//
// Send ETH to make an invest
// Send 0 ETH to payout
// Recomended GAS LIMIT - 150 000
//
// ***WARNING***
// It's a "Ponzi scheme", you can lose your etherium
// You need to send payout request EVERY 24 HOURS
// Contract supports >0 transactions to payout, you can send up to 999 WEI to send payout request
using ToAddress for *;
mapping (address => uint256) invested; // records amounts invested
mapping (address => uint256) lastPaymentBlock; // records blocks at which last payment were made
mapping (address => uint256) dailyPayment; // records estimated daily payment
mapping (address => uint256) totalPaid; // records total paid
address payable constant fundAddress = 0x27FE767C1da8a69731c64F15d6Ee98eE8af62E72; // marketing fund address
function () external payable {
if (msg.value >= 1000) { // receiving function
fundAddress.transfer(msg.value / 10); // sending marketing fee
if (invested[msg.sender] == 0) {lastPaymentBlock[msg.sender] = block.number;} // starting timer of payments (once for address)
invested[msg.sender] += msg.value; // calculating all invests from address
address refAddress = msg.data.toAddr();
if (invested[refAddress] != 0 && refAddress != msg.sender) { invested[refAddress] += msg.value/20; } // Referral bonus adds only to investors
invested[msg.sender] += msg.value/20; // Referral reward
dailyPayment[msg.sender] = (invested[msg.sender] * 2 - totalPaid[msg.sender]) / 40; // calculating amount of daily payment (5% of invest)
} else { // Payment function
if (invested[msg.sender] * 2 > totalPaid[msg.sender] && // max profit = invest*2
block.number - lastPaymentBlock[msg.sender] > 5900) { // 24 hours from last payout
totalPaid[msg.sender] += dailyPayment[msg.sender]; // calculating all payouts
address payable sender = msg.sender; sender.transfer(dailyPayment[msg.sender]); // sending daily profit
}
}
}
}
library ToAddress {
function toAddr(bytes memory source) internal pure returns(address payable addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
} | calculating amount of daily payment (5% of invest)
| dailyPayment[msg.sender] = (invested[msg.sender] * 2 - totalPaid[msg.sender]) / 40; | 6,376,778 | [
1,
12780,
1776,
3844,
434,
18872,
5184,
261,
25,
9,
434,
2198,
395,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
18872,
6032,
63,
3576,
18,
15330,
65,
273,
261,
5768,
3149,
63,
3576,
18,
15330,
65,
380,
576,
300,
2078,
16507,
350,
63,
3576,
18,
15330,
5717,
342,
8063,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x1D6c89Aca9010Dd5a8e890843eaEC1Eb19A3c50d/sources/DOGE.sol | 2% from total supply maxWallet
| maxWallet = 92069000 * 1e18; | 3,639,812 | [
1,
22,
9,
628,
2078,
14467,
943,
16936,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
943,
16936,
273,
2468,
3462,
8148,
3784,
380,
404,
73,
2643,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity ^0.8.0;
import "./interfaces/IRevest.sol";
import "./interfaces/IAddressRegistry.sol";
import "./interfaces/IFeeReporter.sol";
import "./interfaces/IRewardsHandler.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./lib/uniswap/IUniswapV2Router02.sol";
interface IWETH {
function deposit() external payable;
}
contract CashFlowManagement is Ownable, IFeeReporter, ReentrancyGuard {
using SafeERC20 for IERC20;
// Set at deployment to allow for different AMMs on different chains
// Any fork of Uniswap v2 will work
address private immutable UNISWAP_V2_ROUTER;
address private immutable WETH;
uint private constant MAX_INT = 2**256 - 1;
address public addressRegistry;
uint public constant PRECISION = 1 ether;
uint internal erc20Fee = 2;
uint internal weiFee;
// For tracking if a given contract has approval for Uniswap V2 instance
mapping(uint => uint) private approved;
// For tracking if a given contract has approval for token
mapping(address => mapping(address => bool)) private approvedContracts;
constructor(address registry_, address router_, address weth_) {
UNISWAP_V2_ROUTER = router_;
addressRegistry = registry_;
WETH = weth_;
}
function mintTimeLock(
uint[] memory endTimes,
uint[] memory amountPerPeriod,
address[] memory pathToSwaps,
uint slippage // slippage / PRECISION = fraction that represents actual slippage
) external payable nonReentrant returns (uint[] memory fnftIds) {
require(endTimes.length == amountPerPeriod.length, "Invalid arrays");
require(pathToSwaps.length > 1, "Path to swap should be greater than 1");
require(msg.value >= weiFee, 'Insufficient fees!');
bool upfrontPayment = endTimes[0] == 0; // This is the easiest way to indicate immediate payment
uint totalAmountReceived;
uint mul;
{
uint totalAmountToSwap;
for (uint i; i < amountPerPeriod.length; i++) {
totalAmountToSwap += amountPerPeriod[i];
}
// Transfer the tokens from the user to this contract
IERC20(pathToSwaps[0]).safeTransferFrom(
msg.sender,
address(this),
totalAmountToSwap
);
{
uint[] memory amountsOut = IUniswapV2Router02(UNISWAP_V2_ROUTER).getAmountsOut(totalAmountToSwap, pathToSwaps);
uint amtOut = amountsOut[amountsOut.length - 1];
if(!_isApproved(pathToSwaps[0])) {
IERC20(pathToSwaps[0]).approve(UNISWAP_V2_ROUTER, MAX_INT);
_setIsApproved(pathToSwaps[0], true);
}
IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens(
totalAmountToSwap,
amtOut * (PRECISION - slippage) / PRECISION,
pathToSwaps,
address(this),
block.timestamp
);
}
totalAmountReceived = IERC20(pathToSwaps[pathToSwaps.length - 1]).balanceOf(address(this)) * (1000 - erc20Fee) / 1000;
mul = PRECISION * totalAmountReceived / totalAmountToSwap;
}
// Initialize the Revest config object
IRevest.FNFTConfig memory fnftConfig;
// Assign what ERC20 pathToSwaps[0] the FNFT will hold
fnftConfig.asset = pathToSwaps[pathToSwaps.length - 1];
// Set these two arrays according to Revest specifications to say
// Who gets these FNFTs and how many copies of them we should create
address[] memory recipients = new address[](1);
recipients[0] = msg.sender;
uint[] memory quantities = new uint[](1);
quantities[0] = 1;
if(upfrontPayment) {
fnftIds = new uint[](endTimes.length - 1);
} else {
fnftIds = new uint[](endTimes.length);
}
// We use an inline block here to save a little bit of gas + stack
// Allows us to avoid keeping the "address revest" var in memory once
// it has served its purpose
{
// Retrieve the Revest controller address from the address registry
address revest = IAddressRegistry(addressRegistry).getRevest();
// Here, check if the controller has approval to spend tokens out of this entry point contract
if (!approvedContracts[revest][fnftConfig.asset]) {
// If it doesn't, approve it
IERC20(fnftConfig.asset).approve(revest, MAX_INT);
approvedContracts[revest][fnftConfig.asset] = true;
}
// Mint the FNFT
// The return gives us a unique ID we can use to store additional data
for (uint i; i < endTimes.length; i++) {
if(i == 0 && upfrontPayment) {
uint payAmt;
if(i == endTimes.length - 1 ) {
payAmt = totalAmountReceived;
} else {
payAmt = amountPerPeriod[i] * mul / PRECISION;
}
IERC20(fnftConfig.asset).safeTransfer(msg.sender, payAmt);
totalAmountReceived -= payAmt;
} else {
if(i == endTimes.length - 1 ) {
fnftConfig.depositAmount = totalAmountReceived;
} else {
fnftConfig.depositAmount = amountPerPeriod[i] * mul / PRECISION;
}
fnftIds[(upfrontPayment && i > 0) ? i - 1 : i] = IRevest(revest).mintTimeLock{value: (msg.value - weiFee) / endTimes.length}(endTimes[i], recipients, quantities, fnftConfig);
// Avoids issues with division
totalAmountReceived -= fnftConfig.depositAmount;
}
}
if(erc20Fee > 0) {
// Transfer fees to admin contract
address admin = IAddressRegistry(addressRegistry).getAdmin();
uint bal = IERC20(fnftConfig.asset).balanceOf(address(this));
IERC20(fnftConfig.asset).safeTransfer(admin, bal);
}
if(weiFee > 0) {
address rewards = IAddressRegistry(addressRegistry).getRewardsHandler();
IWETH(WETH).deposit{value:weiFee}();
if(!approvedContracts[rewards][WETH]) {
IERC20(WETH).approve(rewards, MAX_INT);
approvedContracts[rewards][WETH] = true;
}
IRewardsHandler(rewards).receiveFee(WETH, weiFee);
}
}
}
function setERC20Fee(uint fee) external onlyOwner {
erc20Fee = fee;
}
function setWeiFee(uint weiFee_) external onlyOwner {
weiFee = weiFee_;
}
function _isApproved(address _owner) internal view returns (bool) {
uint _id = uint(uint160(_owner));
uint _mask = 1 << _id % 256;
return (approved[_id / 256] & _mask) != 0;
}
function _setIsApproved(address _owner, bool _isApprove) internal {
uint _id = uint(uint160(_owner));
if (_isApprove) {
approved[_id / 256] |= 1 << _id % 256;
} else {
approved[_id / 256] &= 0 << _id % 256;
}
}
function getERC20Fee(address) external view override returns (uint) {
return erc20Fee;
}
function getFlatWeiFee(address) external view override returns (uint) {
return weiFee;
}
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
interface IRevest {
event FNFTTimeLockMinted(
address indexed asset,
address indexed from,
uint indexed fnftId,
uint endTime,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTValueLockMinted(
address indexed asset,
address indexed from,
uint indexed fnftId,
address compareTo,
address oracleDispatch,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTAddressLockMinted(
address indexed asset,
address indexed from,
uint indexed fnftId,
address trigger,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTWithdrawn(
address indexed from,
uint indexed fnftId,
uint indexed quantity
);
event FNFTSplit(
address indexed from,
uint[] indexed newFNFTId,
uint[] indexed proportions,
uint quantity
);
event FNFTUnlocked(
address indexed from,
uint indexed fnftId
);
event FNFTMaturityExtended(
address indexed from,
uint indexed fnftId,
uint indexed newExtendedTime
);
event FNFTAddionalDeposited(
address indexed from,
uint indexed newFNFTId,
uint indexed quantity,
uint amount
);
struct FNFTConfig {
address asset; // The token being stored
address pipeToContract; // Indicates if FNFT will pipe to another contract
uint depositAmount; // How many tokens
uint depositMul; // Deposit multiplier
uint split; // Number of splits remaining
uint depositStopTime; //
bool maturityExtension; // Maturity extensions remaining
bool isMulti; //
bool nontransferrable; // False by default (transferrable) //
}
// Refers to the global balance for an ERC20, encompassing possibly many FNFTs
struct TokenTracker {
uint lastBalance;
uint lastMul;
}
enum LockType {
DoesNotExist,
TimeLock,
ValueLock,
AddressLock
}
struct LockParam {
address addressLock;
uint timeLockExpiry;
LockType lockType;
ValueLock valueLock;
}
struct Lock {
address addressLock;
LockType lockType;
ValueLock valueLock;
uint timeLockExpiry;
uint creationTime;
bool unlocked;
}
struct ValueLock {
address asset;
address compareTo;
address oracle;
uint unlockValue;
bool unlockRisingEdge;
}
function mintTimeLock(
uint endTime,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function mintValueLock(
address primaryAsset,
address compareTo,
uint unlockValue,
bool unlockRisingEdge,
address oracleDispatch,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function mintAddressLock(
address trigger,
bytes memory arguments,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function withdrawFNFT(uint tokenUID, uint quantity) external;
function unlockFNFT(uint tokenUID) external;
function splitFNFT(
uint fnftId,
uint[] memory proportions,
uint quantity
) external returns (uint[] memory newFNFTIds);
function depositAdditionalToFNFT(
uint fnftId,
uint amount,
uint quantity
) external returns (uint);
function setFlatWeiFee(uint wethFee) external;
function setERC20Fee(uint erc20) external;
function getFlatWeiFee() external returns (uint);
function getERC20Fee() external returns (uint);
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
/**
* @title Provider interface for Revest FNFTs
* @dev
*
*/
interface IAddressRegistry {
function initialize(
address lock_manager_,
address liquidity_,
address revest_token_,
address token_vault_,
address revest_,
address fnft_,
address metadata_,
address admin_,
address rewards_
) external;
function getAdmin() external view returns (address);
function setAdmin(address admin) external;
function getLockManager() external view returns (address);
function setLockManager(address manager) external;
function getTokenVault() external view returns (address);
function setTokenVault(address vault) external;
function getRevestFNFT() external view returns (address);
function setRevestFNFT(address fnft) external;
function getMetadataHandler() external view returns (address);
function setMetadataHandler(address metadata) external;
function getRevest() external view returns (address);
function setRevest(address revest) external;
function getDEX(uint index) external view returns (address);
function setDex(address dex) external;
function getRevestToken() external view returns (address);
function setRevestToken(address token) external;
function getRewardsHandler() external view returns(address);
function setRewardsHandler(address esc) external;
function getAddress(bytes32 id) external view returns (address);
function getLPs() external view returns (address);
function setLPs(address liquidToken) external;
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
interface IFeeReporter {
function getFlatWeiFee(address asset) external view returns (uint);
function getERC20Fee(address asset) external view returns (uint);
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
interface IRewardsHandler {
struct UserBalance {
uint allocPoint; // Allocation points
uint lastMul;
}
function receiveFee(address token, uint amount) external;
function updateLPShares(uint fnftId, uint newShares) external;
function updateBasicShares(uint fnftId, uint newShares) external;
function getAllocPoint(uint fnftId, address token, bool isBasic) external view returns (uint);
function claimRewards(uint fnftId, address caller) external returns (uint);
function setStakingContract(address stake) external;
function getRewards(uint fnftId, address token) external view returns (uint);
}
// 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/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 (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 (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: UNLICENSED
pragma solidity >=0.8;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// 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/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: UNLICENSED
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
} | Assign what ERC20 pathToSwaps[0] the FNFT will hold | fnftConfig.asset = pathToSwaps[pathToSwaps.length - 1];
| 14,935,840 | [
1,
4910,
4121,
4232,
39,
3462,
12221,
6050,
6679,
63,
20,
65,
326,
27103,
4464,
903,
6887,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2295,
1222,
809,
18,
9406,
273,
12221,
6050,
6679,
63,
803,
774,
6050,
6679,
18,
2469,
300,
404,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/71402/0x2066CAe939E14599f6ED79036b30541328B4C9B6/sources/contracts/relayer/LidoWrapping.sol | No approval is needed here, as wstETH is burned directly from the relayer's account | uint256 result = _wstETH.unwrap(amount);
| 7,092,728 | [
1,
2279,
23556,
353,
3577,
2674,
16,
487,
341,
334,
1584,
44,
353,
18305,
329,
5122,
628,
326,
1279,
1773,
1807,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
563,
273,
389,
91,
334,
1584,
44,
18,
318,
4113,
12,
8949,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
// libraries
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
// interfaces
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol";
import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
import "./interfaces/ICERC20.sol";
import "./interfaces/ICEther.sol";
import "./interfaces/IComptroller.sol";
contract SimpleMarginTrading
{
using LibSafeMath for uint256;
// constants
uint256 constant internal MAX_UINT = uint256(-1);
// contract references
address payable internal owner;
IExchange internal exchange;
IComptroller internal comptroller;
ICERC20 internal cdai;
ICEther internal ceth;
IEtherToken internal weth;
IERC20Token internal dai;
// margin position related variables
uint256 internal positionBalance = 0; // total position size (ETH locked in CETH + WETH + contract balance)
// structs
struct ZeroExQuote {
address buyToken;
address sellToken;
uint256 buyAmount;
uint256 sellAmount;
uint256 protocolFee;
bytes calldataHex;
}
constructor (
address _exchange,
address _comptroller,
address _cdai,
address _dai,
address payable _ceth,
address _weth
)
public
{
exchange = IExchange(_exchange);
comptroller = IComptroller(_comptroller);
cdai = ICERC20(_cdai);
ceth = ICEther(_ceth);
weth = IEtherToken(_weth);
dai = IERC20Token(_dai);
owner = msg.sender;
// Enter markets
_enterMarkets();
}
// receive ETH
function () external payable {
}
// modifiers
modifier onlyOwner() {
require(msg.sender == owner, "permission denied");
_;
}
modifier onlyWhenClosed() {
require(positionBalance == 0, "position not closed");
_;
}
modifier onlyWhenOpen() {
require(positionBalance != 0, "position not open");
_;
}
function _enterMarkets()
internal
{
address[] memory markets = new address[](2);
markets[0] = address(ceth);
markets[1] = address(cdai);
uint[] memory errors = comptroller.enterMarkets(markets);
require(errors[0] == 0, "ceth cant enter market");
require(errors[1] == 0, "cdai cant enter market");
}
function _getZeroExApprovalAddress()
internal
view
returns (address)
{
bytes4 erc20ProxyId = IAssetData(address(0)).ERC20Token.selector;
return exchange.getAssetProxy(erc20ProxyId);
}
function _approve(address token, address delegated)
internal
{
LibERC20Token.approve(token, delegated, MAX_UINT);
}
// TODO: Add a function that executes and verify a 0x swap
// TODO: Add a function that opens a leverage position
// TODO: Add a function that closes the leverage position
// TODO: Add a function that returns the current dai borrow balance
}
| constants contract references margin position related variables structs | {
using LibSafeMath for uint256;
uint256 constant internal MAX_UINT = uint256(-1);
address payable internal owner;
IExchange internal exchange;
IComptroller internal comptroller;
ICERC20 internal cdai;
ICEther internal ceth;
IEtherToken internal weth;
IERC20Token internal dai;
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
struct ZeroExQuote {
address buyToken;
address sellToken;
uint256 buyAmount;
uint256 sellAmount;
uint256 protocolFee;
bytes calldataHex;
}
constructor (
address _exchange,
address _comptroller,
address _cdai,
address _dai,
address payable _ceth,
address _weth
)
public
{
exchange = IExchange(_exchange);
comptroller = IComptroller(_comptroller);
cdai = ICERC20(_cdai);
ceth = ICEther(_ceth);
weth = IEtherToken(_weth);
dai = IERC20Token(_dai);
owner = msg.sender;
_enterMarkets();
}
function () external payable {
}
modifier onlyOwner() {
require(msg.sender == owner, "permission denied");
_;
}
modifier onlyWhenClosed() {
require(positionBalance == 0, "position not closed");
_;
}
modifier onlyWhenOpen() {
require(positionBalance != 0, "position not open");
_;
}
function _enterMarkets()
internal
{
address[] memory markets = new address[](2);
markets[0] = address(ceth);
markets[1] = address(cdai);
uint[] memory errors = comptroller.enterMarkets(markets);
require(errors[0] == 0, "ceth cant enter market");
require(errors[1] == 0, "cdai cant enter market");
}
function _getZeroExApprovalAddress()
internal
view
returns (address)
{
bytes4 erc20ProxyId = IAssetData(address(0)).ERC20Token.selector;
return exchange.getAssetProxy(erc20ProxyId);
}
function _approve(address token, address delegated)
internal
{
LibERC20Token.approve(token, delegated, MAX_UINT);
}
}
| 12,697,408 | [
1,
13358,
6835,
5351,
7333,
1754,
3746,
3152,
8179,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1450,
10560,
9890,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
5381,
2713,
4552,
67,
57,
3217,
273,
2254,
5034,
19236,
21,
1769,
203,
203,
565,
1758,
8843,
429,
2713,
3410,
31,
203,
565,
467,
11688,
2713,
7829,
31,
203,
565,
467,
799,
337,
1539,
2713,
532,
337,
1539,
31,
203,
565,
26899,
654,
39,
3462,
2713,
276,
2414,
77,
31,
203,
565,
467,
1441,
1136,
2713,
276,
546,
31,
203,
565,
10897,
1136,
1345,
2713,
341,
546,
31,
203,
565,
467,
654,
39,
3462,
1345,
2713,
5248,
77,
31,
203,
203,
203,
5666,
8787,
20,
92,
19,
16351,
87,
17,
16641,
17,
21571,
19,
16351,
87,
19,
4816,
19,
5664,
8026,
3447,
18,
18281,
14432,
203,
5666,
8787,
20,
92,
19,
16351,
87,
17,
12610,
3462,
19,
16351,
87,
19,
4816,
19,
15898,
19,
45,
654,
39,
3462,
1345,
18,
18281,
14432,
203,
565,
1958,
12744,
424,
10257,
288,
203,
3639,
1758,
30143,
1345,
31,
203,
3639,
1758,
357,
80,
1345,
31,
203,
3639,
2254,
5034,
30143,
6275,
31,
203,
3639,
2254,
5034,
357,
80,
6275,
31,
203,
3639,
2254,
5034,
1771,
14667,
31,
203,
3639,
1731,
745,
892,
7037,
31,
203,
565,
289,
203,
203,
565,
3885,
261,
203,
3639,
1758,
389,
16641,
16,
203,
3639,
1758,
389,
832,
337,
1539,
16,
203,
3639,
1758,
389,
71,
2414,
77,
16,
203,
3639,
1758,
389,
2414,
77,
16,
203,
3639,
1758,
8843,
429,
389,
71,
546,
16,
203,
3639,
1758,
389,
91,
546,
203,
3639,
262,
203,
3639,
2
] |
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract Ether2AI is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "Ether2AI";
symbol = "ETH2AI";
decimals = 18;
_totalSupply = 60000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "Ether2AI";
symbol = "ETH2AI";
decimals = 18;
_totalSupply = 60000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 12,020,210 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
41,
1136,
22,
18194,
14432,
203,
3639,
3273,
273,
315,
1584,
44,
22,
18194,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
1666,
12648,
12648,
12648,
2787,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x4620C2d52C589840A8eE800F36B9b2E0e704Af08/sources/contracts/valentinu.sol | Limiting early mover's advantage | totalFee = 20;
| 8,140,740 | [
1,
3039,
310,
11646,
312,
1643,
1807,
1261,
7445,
410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
10792,
2078,
14667,
273,
4200,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x411F2DD2514F6D26707Cc06A16719fd33B76fAd6/sources/Overmoon.sol | Adding Variables for all the routers for easier deployment for our customers. | constructor() ERC20("Overmoon", "OVERMOON") {
address _owner = 0x2DA12c40bf09B73E4999D555DBC792a133259ea3;
_decimals = 18;
uint256 totalSupply = 1000000000000000 * (10**_decimals);
buyMarketingFee = 0;
buyLiquidityFee = 0;
buyDevFee = 0;
buyBuyBackFee = 0;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyBuyBackFee;
sellMarketingFee = 0;
sellLiquidityFee = 0;
sellDevFee = 0;
sellBuyBackFee = 0;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellBuyBackFee;
address currentRouter;
if (block.chainid == 56) {
revert();
}
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(currentRouter);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(_owner, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
| 15,967,989 | [
1,
13962,
23536,
364,
777,
326,
28944,
364,
15857,
6314,
364,
3134,
29380,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
4851,
8683,
265,
3113,
315,
12959,
5980,
673,
7923,
288,
203,
203,
3639,
1758,
389,
8443,
273,
374,
92,
22,
9793,
2138,
71,
7132,
17156,
5908,
38,
9036,
41,
24,
11984,
40,
2539,
25,
13183,
7235,
22,
69,
3437,
1578,
6162,
24852,
23,
31,
203,
203,
3639,
389,
31734,
273,
6549,
31,
203,
203,
3639,
2254,
5034,
2078,
3088,
1283,
273,
2130,
12648,
11706,
380,
261,
2163,
636,
67,
31734,
1769,
203,
540,
203,
203,
3639,
30143,
3882,
21747,
14667,
273,
374,
31,
203,
3639,
30143,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
30143,
8870,
14667,
273,
374,
31,
203,
3639,
30143,
38,
9835,
2711,
14667,
273,
374,
31,
203,
3639,
30143,
5269,
2954,
281,
273,
30143,
3882,
21747,
14667,
397,
30143,
48,
18988,
24237,
14667,
397,
30143,
8870,
14667,
397,
30143,
38,
9835,
2711,
14667,
31,
203,
540,
203,
3639,
357,
80,
3882,
21747,
14667,
273,
374,
31,
203,
3639,
357,
80,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
357,
80,
8870,
14667,
273,
374,
31,
203,
3639,
357,
80,
38,
9835,
2711,
14667,
273,
374,
31,
203,
3639,
357,
80,
5269,
2954,
281,
273,
357,
80,
3882,
21747,
14667,
397,
357,
80,
48,
18988,
24237,
14667,
397,
357,
80,
8870,
14667,
397,
357,
80,
38,
9835,
2711,
14667,
31,
203,
203,
203,
203,
3639,
1758,
783,
8259,
31,
203,
540,
203,
3639,
309,
261,
2629,
18,
5639,
350,
422,
13850,
13,
288,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../ManagerProxyTarget.sol";
import "./IBondingManager.sol";
import "../libraries/SortedDoublyLL.sol";
import "../libraries/MathUtils.sol";
import "../libraries/PreciseMathUtils.sol";
import "./libraries/EarningsPool.sol";
import "./libraries/EarningsPoolLIP36.sol";
import "../token/ILivepeerToken.sol";
import "../token/IMinter.sol";
import "../rounds/IRoundsManager.sol";
import "../snapshots/IMerkleSnapshot.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title BondingManager
* @notice Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol
*/
contract BondingManager is ManagerProxyTarget, IBondingManager {
using SafeMath for uint256;
using SortedDoublyLL for SortedDoublyLL.Data;
using EarningsPool for EarningsPool.Data;
using EarningsPoolLIP36 for EarningsPool.Data;
// Constants
// Occurances are replaced at compile time
// and computed to a single value if possible by the optimizer
uint256 constant MAX_FUTURE_ROUND = 2**256 - 1;
// Time between unbonding and possible withdrawl in rounds
uint64 public unbondingPeriod;
// Represents a transcoder's current state
struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
mapping(uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round
uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut).
uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share)
uint256 lastFeeRound; // Latest round in which the transcoder received fees
}
// The various states a transcoder can be in
enum TranscoderStatus {
NotRegistered,
Registered
}
// Represents a delegator's current state
struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping(uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
}
// The various states a delegator can be in
enum DelegatorStatus {
Pending,
Bonded,
Unbonded
}
// Represents an amount of tokens that are being unbonded
struct UnbondingLock {
uint256 amount; // Amount of tokens being unbonded
uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn
}
// Keep track of the known transcoders and delegators
mapping(address => Delegator) private delegators;
mapping(address => Transcoder) private transcoders;
// The total active stake (sum of the stake of active set members) for the current round
uint256 public currentRoundTotalActiveStake;
// The total active stake (sum of the stake of active set members) for the next round
uint256 public nextRoundTotalActiveStake;
// The transcoder pool is used to keep track of the transcoders that are eligible for activation.
// The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders
// in the pool are locked into the active set for round N + 1
SortedDoublyLL.Data private transcoderPool;
// Check if sender is TicketBroker
modifier onlyTicketBroker() {
_onlyTicketBroker();
_;
}
// Check if sender is RoundsManager
modifier onlyRoundsManager() {
_onlyRoundsManager();
_;
}
// Check if sender is Verifier
modifier onlyVerifier() {
_onlyVerifier();
_;
}
// Check if current round is initialized
modifier currentRoundInitialized() {
_currentRoundInitialized();
_;
}
// Automatically claim earnings from lastClaimRound through the current round
modifier autoClaimEarnings() {
_autoClaimEarnings();
_;
}
/**
* @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address
* @dev This constructor will not initialize any state variables besides `controller`. The following setter functions
* should be used to initialize state variables post-deployment:
* - setUnbondingPeriod()
* - setNumActiveTranscoders()
* - setMaxEarningsClaimsRounds()
* @param _controller Address of Controller that this contract will be registered with
*/
constructor(address _controller) Manager(_controller) {}
/**
* @notice Set unbonding period. Only callable by Controller owner
* @param _unbondingPeriod Rounds between unbonding and possible withdrawal
*/
function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner {
unbondingPeriod = _unbondingPeriod;
emit ParameterUpdate("unbondingPeriod");
}
/**
* @notice Set maximum number of active transcoders. Only callable by Controller owner
* @param _numActiveTranscoders Number of active transcoders
*/
function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner {
transcoderPool.setMaxSize(_numActiveTranscoders);
emit ParameterUpdate("numActiveTranscoders");
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
*/
function transcoder(uint256 _rewardCut, uint256 _feeShare) external {
transcoderWithHint(_rewardCut, _feeShare, address(0), address(0));
}
/**
* @notice Delegate stake towards a specific address
* @param _amount The amount of tokens to stake
* @param _to The address of the transcoder to stake towards
*/
function bond(uint256 _amount, address _to) external {
bondWithHint(_amount, _to, address(0), address(0), address(0), address(0));
}
/**
* @notice Unbond an amount of the delegator's bonded stake
* @param _amount Amount of tokens to unbond
*/
function unbond(uint256 _amount) external {
unbondWithHint(_amount, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebond(uint256 _unbondingLockId) external {
rebondWithHint(_unbondingLockId, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external {
rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0));
}
/**
* @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period
* @param _unbondingLockId ID of unbonding lock to withdraw with
*/
function withdrawStake(uint256 _unbondingLockId) external whenSystemNotPaused currentRoundInitialized {
Delegator storage del = delegators[msg.sender];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID");
require(
lock.withdrawRound <= roundsManager().currentRound(),
"withdraw round must be before or equal to the current round"
);
uint256 amount = lock.amount;
uint256 withdrawRound = lock.withdrawRound;
// Delete unbonding lock
delete del.unbondingLocks[_unbondingLockId];
// Tell Minter to transfer stake (LPT) to the delegator
minter().trustedTransferTokens(msg.sender, amount);
emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound);
}
/**
* @notice Withdraws fees to the caller
*/
function withdrawFees(address payable _recipient, uint256 _amount)
external
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(_recipient != address(0), "invalid recipient");
uint256 fees = delegators[msg.sender].fees;
require(fees >= _amount, "insufficient fees to withdraw");
delegators[msg.sender].fees = fees.sub(_amount);
// Tell Minter to transfer fees (ETH) to the address
minter().trustedWithdrawETH(_recipient, _amount);
emit WithdrawFees(msg.sender, _recipient, _amount);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators
*/
function reward() external {
rewardWithHint(address(0), address(0));
}
/**
* @notice Update transcoder's fee pool. Only callable by the TicketBroker
* @param _transcoder Transcoder address
* @param _fees Fees to be added to the fee pool
*/
function updateTranscoderWithFees(
address _transcoder,
uint256 _fees,
uint256 _round
) external whenSystemNotPaused onlyTicketBroker {
// Silence unused param compiler warning
_round;
require(isRegisteredTranscoder(_transcoder), "transcoder must be registered");
uint256 currentRound = roundsManager().currentRound();
Transcoder storage t = transcoders[_transcoder];
uint256 lastRewardRound = t.lastRewardRound;
uint256 activeCumulativeRewards = t.activeCumulativeRewards;
// LIP-36: Add fees for the current round instead of '_round'
// https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1));
// if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake'
// on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected
// for cumulative fee calculation this would result in division by zero.
if (currentRound > lastRewardRound) {
earningsPool.setCommission(t.rewardCut, t.feeShare);
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not
// yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its
// current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become
// the transcoder's activeCumulativeRewards if it calls reward() later on in the current round
activeCumulativeRewards = t.cumulativeRewards;
}
uint256 totalStake = earningsPool.totalStake;
if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) {
// if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call)
// retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder)
// based on rewards for currentRound
IMinter mtr = minter();
uint256 rewards = PreciseMathUtils.percOf(
mtr.currentMintableTokens().add(mtr.currentMintedTokens()),
totalStake,
currentRoundTotalActiveStake
);
uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards);
prevEarningsPool.cumulativeRewardFactor = PreciseMathUtils.percOf(
earningsPool.cumulativeRewardFactor,
totalStake,
delegatorsRewards.add(totalStake)
);
}
uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare);
uint256 transcoderCommissionFees = _fees.sub(delegatorsFees);
// Calculate the fees earned by the transcoder's earned rewards
uint256 transcoderRewardStakeFees = PreciseMathUtils.percOf(
delegatorsFees,
activeCumulativeRewards,
totalStake
);
// Track fees earned by the transcoder based on its earned rewards and feeShare
t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees);
// Update cumulative fee factor with new fees
// The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated)
// Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field
earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees);
t.lastFeeRound = currentRound;
}
/**
* @notice Slash a transcoder. Only callable by the Verifier
* @param _transcoder Transcoder address
* @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder
* @param _slashAmount Percentage of transcoder bond to be slashed
* @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder
*/
function slashTranscoder(
address _transcoder,
address _finder,
uint256 _slashAmount,
uint256 _finderFee
) external whenSystemNotPaused onlyVerifier {
Delegator storage del = delegators[_transcoder];
if (del.bondedAmount > 0) {
uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);
// If active transcoder, resign it
if (transcoderPool.contains(_transcoder)) {
resignTranscoder(_transcoder);
}
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
// If still bonded decrease delegate's delegated amount
if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(
penalty
);
}
// Account for penalty
uint256 burnAmount = penalty;
// Award finder fee if there is a finder address
if (_finder != address(0)) {
uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);
minter().trustedTransferTokens(_finder, finderAmount);
// Minter burns the slashed funds - finder reward
minter().trustedBurnTokens(burnAmount.sub(finderAmount));
emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);
} else {
// Minter burns the slashed funds
minter().trustedBurnTokens(burnAmount);
emit TranscoderSlashed(_transcoder, address(0), penalty, 0);
}
} else {
emit TranscoderSlashed(_transcoder, _finder, 0, 0);
}
}
/**
* @notice Claim token pools shares for a delegator from its lastClaimRound through the end round
* @param _endRound The last round for which to claim token pools shares for a delegator
*/
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {
// Silence unused param compiler warning
_endRound;
_autoClaimEarnings();
}
/**
* @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager
*/
function setCurrentRoundTotalActiveStake() external onlyRoundsManager {
currentRoundTotalActiveStake = nextRoundTotalActiveStake;
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the
* caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will
* be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed.
* See SortedDoublyLL.sol for details on list hints
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
* @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool
* @param _newPosNext Address of next transcoder in pool if the caller joins the pool
*/
function transcoderWithHint(
uint256 _rewardCut,
uint256 _feeShare,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized {
require(!roundsManager().currentRoundLocked(), "can't update transcoder params, current round is locked");
require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage");
require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage");
require(isRegisteredTranscoder(msg.sender), "transcoder must be registered");
Transcoder storage t = transcoders[msg.sender];
uint256 currentRound = roundsManager().currentRound();
require(
!isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound,
"caller can't be active or must have already called reward for the current round"
);
t.rewardCut = _rewardCut;
t.feeShare = _feeShare;
if (!transcoderPool.contains(msg.sender)) {
tryToJoinActiveSet(
msg.sender,
delegators[msg.sender].delegatedAmount,
currentRound.add(1),
_newPosPrev,
_newPosNext
);
}
emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare);
}
/**
* @notice Delegates stake "on behalf of" another address towards a specific address
* and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _owner The address of the owner of the bond
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondForWithHint(
uint256 _amount,
address _owner,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
Delegator storage del = delegators[_owner];
uint256 currentRound = roundsManager().currentRound();
// Amount to delegate
uint256 delegationAmount = _amount;
// Current delegate
address currentDelegate = del.delegateAddress;
// Current bonded amount
uint256 currentBondedAmount = del.bondedAmount;
if (delegatorStatus(_owner) == DelegatorStatus.Unbonded) {
// New delegate
// Set start round
// Don't set start round if delegator is in pending state because the start round would not change
del.startRound = currentRound.add(1);
// Unbonded state = no existing delegate and no bonded stake
// Thus, delegation amount = provided amount
} else if (currentBondedAmount > 0 && currentDelegate != _to) {
// A registered transcoder cannot delegate its bonded stake toward another address
// because it can only be delegated toward itself
// In the future, if delegation towards another registered transcoder as an already
// registered transcoder becomes useful (i.e. for transitive delegation), this restriction
// could be removed
require(!isRegisteredTranscoder(_owner), "registered transcoders can't delegate towards other addresses");
// Changing delegate
// Set start round
del.startRound = currentRound.add(1);
// Update amount to delegate with previous delegation amount
delegationAmount = delegationAmount.add(currentBondedAmount);
decreaseTotalStake(currentDelegate, currentBondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
}
{
Transcoder storage newDelegate = transcoders[_to];
EarningsPool.Data storage currPool = newDelegate.earningsPoolPerRound[currentRound];
if (currPool.cumulativeRewardFactor == 0) {
currPool.cumulativeRewardFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastRewardRound)
.cumulativeRewardFactor;
}
if (currPool.cumulativeFeeFactor == 0) {
currPool.cumulativeFeeFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastFeeRound)
.cumulativeFeeFactor;
}
}
// cannot delegate to someone without having bonded stake
require(delegationAmount > 0, "delegation amount must be greater than 0");
// Update delegate
del.delegateAddress = _to;
// Update bonded amount
del.bondedAmount = currentBondedAmount.add(_amount);
increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext);
if (_amount > 0) {
// Transfer the LPT to the Minter
livepeerToken().transferFrom(msg.sender, address(minter()), _amount);
}
emit Bond(_to, currentDelegate, _owner, _amount, del.bondedAmount);
}
/**
* @notice Delegates stake towards a specific address and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondWithHint(
uint256 _amount,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
) public {
bondForWithHint(
_amount,
msg.sender,
_to,
_oldDelegateNewPosPrev,
_oldDelegateNewPosNext,
_currDelegateNewPosPrev,
_currDelegateNewPosNext
);
}
/**
* @notice Transfers ownership of a bond to a new delegator using optional hints if needed
*
* If the receiver is already bonded to a different delegate than the bond owner then the stake goes
* to the receiver's delegate otherwise the receiver's delegate is set as the owner's delegate
*
* @dev If the original delegate is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the target delegate is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_newDelegateNewPosPrev` and `_newDelegateNewPosNext` params.
*
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Receiver of the bond
* @param _amount Portion of the bond to transfer to receiver
* @param _oldDelegateNewPosPrev Address of previous transcoder in pool if the delegate remains in the pool
* @param _oldDelegateNewPosNext Address of next transcoder in pool if the delegate remains in the pool
* @param _newDelegateNewPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newDelegateNewPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function transferBond(
address _delegator,
uint256 _amount,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _newDelegateNewPosPrev,
address _newDelegateNewPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
Delegator storage oldDel = delegators[msg.sender];
// Cache delegate address of caller before unbondWithHint because
// if unbondWithHint is for a full unbond the caller's delegate address will be set to null
address oldDelDelegate = oldDel.delegateAddress;
unbondWithHint(_amount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
Delegator storage newDel = delegators[_delegator];
uint256 oldDelUnbondingLockId = oldDel.nextUnbondingLockId.sub(1);
uint256 withdrawRound = oldDel.unbondingLocks[oldDelUnbondingLockId].withdrawRound;
// Burn lock for current owner
delete oldDel.unbondingLocks[oldDelUnbondingLockId];
// Create lock for new owner
uint256 newDelUnbondingLockId = newDel.nextUnbondingLockId;
newDel.unbondingLocks[newDelUnbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound });
newDel.nextUnbondingLockId = newDel.nextUnbondingLockId.add(1);
emit TransferBond(msg.sender, _delegator, oldDelUnbondingLockId, newDelUnbondingLockId, _amount);
// Claim earnings for receiver before processing unbonding lock
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = newDel.lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(_delegator, currentRound, lastClaimRound);
}
// Rebond lock for new owner
if (newDel.delegateAddress == address(0)) {
newDel.delegateAddress = oldDelDelegate;
}
// Move to Pending state if receiver is currently in Unbonded state
if (delegatorStatus(_delegator) == DelegatorStatus.Unbonded) {
newDel.startRound = currentRound.add(1);
}
// Process rebond using unbonding lock
processRebond(_delegator, newDelUnbondingLockId, _newDelegateNewPosPrev, _newDelegateNewPosNext);
}
/**
* @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed
* @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _amount Amount of tokens to unbond
* @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool
* @param _newPosNext Address of next transcoder in pool if the caller remains in the pool
*/
function unbondWithHint(
uint256 _amount,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
// Create new unbonding lock
del.unbondingLocks[unbondingLockId] = UnbondingLock({ amount: _amount, withdrawRound: withdrawRound });
// Increment ID for next unbonding lock
del.nextUnbondingLockId = unbondingLockId.add(1);
// Decrease delegator's bonded amount
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
// Delegator no longer delegated to anyone if it does not have a bonded amount
del.delegateAddress = address(0);
// Delegator does not have a start round if it is no longer delegated to anyone
del.startRound = 0;
if (transcoderPool.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
// If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount
decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext);
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates
* the transcoder pool using an optional list hint if needed
* @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function rebondWithHint(
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded");
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using
* an optional list hint if needed
* @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate joins the pool
*/
function rebondFromUnbondedWithHint(
address _to,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded");
// Set delegator's start round and transition into Pending state
delegators[msg.sender].startRound = roundsManager().currentRound().add(1);
// Set delegator's delegate
delegators[msg.sender].delegateAddress = _to;
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed
* @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool
* @param _newPosNext Address of next transcoder in pool if the caller is in the pool
*/
function rewardWithHint(address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
{
uint256 currentRound = roundsManager().currentRound();
require(isActiveTranscoder(msg.sender), "caller must be an active transcoder");
require(
transcoders[msg.sender].lastRewardRound != currentRound,
"caller has already called reward for the current round"
);
Transcoder storage t = transcoders[msg.sender];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
// Set last round that transcoder called reward
earningsPool.setCommission(t.rewardCut, t.feeShare);
// If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round
// the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized
// Thus we sync the the transcoder's stake to when it was last updated
// 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// Create reward based on active transcoder's stake relative to the total active stake
// rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake
uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake);
updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext);
// Set last round that transcoder called reward
t.lastRewardRound = currentRound;
emit Reward(msg.sender, rewardTokens);
}
/**
* @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending stake from
* @return Pending bonded stake for '_delegator' since last claiming rewards
*/
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {
// Silence unused param compiler warning
_endRound;
uint256 endRound = roundsManager().currentRound();
(uint256 stake, ) = pendingStakeAndFees(_delegator, endRound);
return stake;
}
/**
* @notice Returns pending fees for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending fees from
* @return Pending fees for '_delegator' since last claiming fees
*/
function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) {
// Silence unused param compiler warning
_endRound;
uint256 endRound = roundsManager().currentRound();
(, uint256 fees) = pendingStakeAndFees(_delegator, endRound);
return fees;
}
/**
* @notice Returns total bonded stake for a transcoder
* @param _transcoder Address of transcoder
* @return total bonded stake for a delegator
*/
function transcoderTotalStake(address _transcoder) public view returns (uint256) {
return delegators[_transcoder].delegatedAmount;
}
/**
* @notice Computes transcoder status
* @param _transcoder Address of transcoder
* @return registered or not registered transcoder status
*/
function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) {
if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered;
return TranscoderStatus.NotRegistered;
}
/**
* @notice Computes delegator status
* @param _delegator Address of delegator
* @return bonded, unbonded or pending delegator status
*/
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {
Delegator storage del = delegators[_delegator];
if (del.bondedAmount == 0) {
// Delegator unbonded all its tokens
return DelegatorStatus.Unbonded;
} else if (del.startRound > roundsManager().currentRound()) {
// Delegator round start is in the future
return DelegatorStatus.Pending;
} else {
// Delegator round start is now or in the past
// del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which
// would trigger the first if clause
return DelegatorStatus.Bonded;
}
}
/**
* @notice Return transcoder information
* @param _transcoder Address of transcoder
* @return lastRewardRound Trancoder's last reward round
* @return rewardCut Transcoder's reward cut
* @return feeShare Transcoder's fee share
* @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active
* @return activationRound Round in which transcoder became active
* @return deactivationRound Round in which transcoder will no longer be active
* @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active
* @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut)
* @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share)
* @return lastFeeRound Latest round that the transcoder received fees
*/
function getTranscoder(address _transcoder)
public
view
returns (
uint256 lastRewardRound,
uint256 rewardCut,
uint256 feeShare,
uint256 lastActiveStakeUpdateRound,
uint256 activationRound,
uint256 deactivationRound,
uint256 activeCumulativeRewards,
uint256 cumulativeRewards,
uint256 cumulativeFees,
uint256 lastFeeRound
)
{
Transcoder storage t = transcoders[_transcoder];
lastRewardRound = t.lastRewardRound;
rewardCut = t.rewardCut;
feeShare = t.feeShare;
lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound;
activationRound = t.activationRound;
deactivationRound = t.deactivationRound;
activeCumulativeRewards = t.activeCumulativeRewards;
cumulativeRewards = t.cumulativeRewards;
cumulativeFees = t.cumulativeFees;
lastFeeRound = t.lastFeeRound;
}
/**
* @notice Return transcoder's earnings pool for a given round
* @param _transcoder Address of transcoder
* @param _round Round number
* @return totalStake Transcoder's total stake in '_round'
* @return transcoderRewardCut Transcoder's reward cut for '_round'
* @return transcoderFeeShare Transcoder's fee share for '_round'
* @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36)
* @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36)
*/
function getTranscoderEarningsPoolForRound(address _transcoder, uint256 _round)
public
view
returns (
uint256 totalStake,
uint256 transcoderRewardCut,
uint256 transcoderFeeShare,
uint256 cumulativeRewardFactor,
uint256 cumulativeFeeFactor
)
{
EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];
totalStake = earningsPool.totalStake;
transcoderRewardCut = earningsPool.transcoderRewardCut;
transcoderFeeShare = earningsPool.transcoderFeeShare;
cumulativeRewardFactor = earningsPool.cumulativeRewardFactor;
cumulativeFeeFactor = earningsPool.cumulativeFeeFactor;
}
/**
* @notice Return delegator info
* @param _delegator Address of delegator
* @return bondedAmount total amount bonded by '_delegator'
* @return fees amount of fees collected by '_delegator'
* @return delegateAddress address '_delegator' has bonded to
* @return delegatedAmount total amount delegated to '_delegator'
* @return startRound round in which bond for '_delegator' became effective
* @return lastClaimRound round for which '_delegator' has last claimed earnings
* @return nextUnbondingLockId ID for the next unbonding lock created for '_delegator'
*/
function getDelegator(address _delegator)
public
view
returns (
uint256 bondedAmount,
uint256 fees,
address delegateAddress,
uint256 delegatedAmount,
uint256 startRound,
uint256 lastClaimRound,
uint256 nextUnbondingLockId
)
{
Delegator storage del = delegators[_delegator];
bondedAmount = del.bondedAmount;
fees = del.fees;
delegateAddress = del.delegateAddress;
delegatedAmount = del.delegatedAmount;
startRound = del.startRound;
lastClaimRound = del.lastClaimRound;
nextUnbondingLockId = del.nextUnbondingLockId;
}
/**
* @notice Return delegator's unbonding lock info
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return amount of stake locked up by unbonding lock
* @return withdrawRound round in which 'amount' becomes available for withdrawal
*/
function getDelegatorUnbondingLock(address _delegator, uint256 _unbondingLockId)
public
view
returns (uint256 amount, uint256 withdrawRound)
{
UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId];
return (lock.amount, lock.withdrawRound);
}
/**
* @notice Returns max size of transcoder pool
* @return transcoder pool max size
*/
function getTranscoderPoolMaxSize() public view returns (uint256) {
return transcoderPool.getMaxSize();
}
/**
* @notice Returns size of transcoder pool
* @return transcoder pool current size
*/
function getTranscoderPoolSize() public view returns (uint256) {
return transcoderPool.getSize();
}
/**
* @notice Returns transcoder with most stake in pool
* @return address for transcoder with highest stake in transcoder pool
*/
function getFirstTranscoderInPool() public view returns (address) {
return transcoderPool.getFirst();
}
/**
* @notice Returns next transcoder in pool for a given transcoder
* @param _transcoder Address of a transcoder in the pool
* @return address for the transcoder after '_transcoder' in transcoder pool
*/
function getNextTranscoderInPool(address _transcoder) public view returns (address) {
return transcoderPool.getNext(_transcoder);
}
/**
* @notice Return total bonded tokens
* @return total active stake for the current round
*/
function getTotalBonded() public view returns (uint256) {
return currentRoundTotalActiveStake;
}
/**
* @notice Return whether a transcoder is active for the current round
* @param _transcoder Transcoder address
* @return true if transcoder is active
*/
function isActiveTranscoder(address _transcoder) public view returns (bool) {
Transcoder storage t = transcoders[_transcoder];
uint256 currentRound = roundsManager().currentRound();
return t.activationRound <= currentRound && currentRound < t.deactivationRound;
}
/**
* @notice Return whether a transcoder is registered
* @param _transcoder Transcoder address
* @return true if transcoder is self-bonded
*/
function isRegisteredTranscoder(address _transcoder) public view returns (bool) {
Delegator storage d = delegators[_transcoder];
return d.delegateAddress == _transcoder && d.bondedAmount > 0;
}
/**
* @notice Return whether an unbonding lock for a delegator is valid
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return true if unbondingLock for ID has a non-zero withdraw round
*/
function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) {
// A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero)
return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0;
}
/**
* @notice Return an EarningsPool.Data struct with cumulative factors for a given round that are rescaled if needed
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the cumulative factors for
*/
function cumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round)
internal
view
returns (EarningsPool.Data memory pool)
{
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor;
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor;
return pool;
}
/**
* @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the latest cumulative factors for
* @return pool An EarningsPool.Data populated with the latest cumulative factors for _round
*/
function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round)
internal
view
returns (EarningsPool.Data memory pool)
{
pool = cumulativeFactorsPool(_transcoder, _round);
uint256 lastRewardRound = _transcoder.lastRewardRound;
// Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round
if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) {
pool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lastRewardRound).cumulativeRewardFactor;
}
uint256 lastFeeRound = _transcoder.lastFeeRound;
// Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round
if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) {
pool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lastFeeRound).cumulativeFeeFactor;
}
return pool;
}
/**
* @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm
* @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate
* @param _startRound The round for the start cumulative factors
* @param _endRound The round for the end cumulative factors
* @param _stake The delegator's initial stake before including earned rewards
* @param _fees The delegator's initial fees before including earned fees
* @return cStake , cFees where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees
*/
function delegatorCumulativeStakeAndFees(
Transcoder storage _transcoder,
uint256 _startRound,
uint256 _endRound,
uint256 _stake,
uint256 _fees
) internal view returns (uint256 cStake, uint256 cFees) {
// Fetch start cumulative factors
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
// If the start cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1)
if (startPool.cumulativeRewardFactor == 0) {
startPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1);
}
// Fetch end cumulative factors
EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound);
// If the end cumulativeRewardFactor is 0 set the default value to PreciseMathUtils.percPoints(1, 1)
if (endPool.cumulativeRewardFactor == 0) {
endPool.cumulativeRewardFactor = PreciseMathUtils.percPoints(1, 1);
}
cFees = _fees.add(
PreciseMathUtils.percOf(
_stake,
endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor),
startPool.cumulativeRewardFactor
)
);
cStake = PreciseMathUtils.percOf(_stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor);
return (cStake, cFees);
}
/**
* @notice Return the pending stake and fees for a delegator
* @param _delegator Address of a delegator
* @param _endRound The last round to claim earnings for when calculating the pending stake and fees
* @return stake , fees where stake is the delegator's pending stake and fees is the delegator's pending fees
*/
function pendingStakeAndFees(address _delegator, uint256 _endRound)
internal
view
returns (uint256 stake, uint256 fees)
{
Delegator storage del = delegators[_delegator];
Transcoder storage t = transcoders[del.delegateAddress];
fees = del.fees;
stake = del.bondedAmount;
uint256 startRound = del.lastClaimRound.add(1);
address delegateAddr = del.delegateAddress;
bool isTranscoder = _delegator == delegateAddr;
// Make sure there is a round to claim i.e. end round - (start round - 1) > 0
if (startRound <= _endRound) {
(stake, fees) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees);
}
// cumulativeRewards and cumulativeFees will track *all* rewards/fees earned by the transcoder
// so it is important that this is only executed with the end round as the current round or else
// the returned stake and fees will reflect rewards/fees earned in the future relative to the end round
if (isTranscoder) {
stake = stake.add(t.cumulativeRewards);
fees = fees.add(t.cumulativeFees);
}
return (stake, fees);
}
/**
* @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The delegate to increase the stake for
* @param _amount The amount to increase the stake for '_delegate' by
*/
function increaseTotalStake(
address _delegate,
uint256 _amount,
address _newPosPrev,
address _newPosNext
) internal {
if (isRegisteredTranscoder(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.add(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
// If the transcoder is already in the active set update its stake and return
if (transcoderPool.contains(_delegate)) {
transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.earningsPoolPerRound[nextRound].setStake(newStake);
t.lastActiveStakeUpdateRound = nextRound;
} else {
// Check if the transcoder is eligible to join the active set in the update round
tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext);
}
}
// Increase delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount);
}
/**
* @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The transcoder to decrease the stake for
* @param _amount The amount to decrease the stake for '_delegate' by
*/
function decreaseTotalStake(
address _delegate,
uint256 _amount,
address _newPosPrev,
address _newPosNext
) internal {
if (transcoderPool.contains(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.sub(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
transcoderPool.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.lastActiveStakeUpdateRound = nextRound;
t.earningsPoolPerRound[nextRound].setStake(newStake);
}
// Decrease old delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount);
}
/**
* @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full
* @param _transcoder The transcoder to insert into the transcoder pool
* @param _totalStake The total stake for '_transcoder'
* @param _activationRound The round in which the transcoder should become active
*/
function tryToJoinActiveSet(
address _transcoder,
uint256 _totalStake,
uint256 _activationRound,
address _newPosPrev,
address _newPosNext
) internal {
uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake;
if (transcoderPool.isFull()) {
address lastTranscoder = transcoderPool.getLast();
uint256 lastStake = transcoderTotalStake(lastTranscoder);
// If the pool is full and the transcoder has less stake than the least stake transcoder in the pool
// then the transcoder is unable to join the active set for the next round
if (_totalStake <= lastStake) {
return;
}
// Evict the least stake transcoder from the active set for the next round
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPool.remove(lastTranscoder);
transcoders[lastTranscoder].deactivationRound = _activationRound;
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake);
emit TranscoderDeactivated(lastTranscoder, _activationRound);
}
transcoderPool.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext);
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake);
Transcoder storage t = transcoders[_transcoder];
t.lastActiveStakeUpdateRound = _activationRound;
t.activationRound = _activationRound;
t.deactivationRound = MAX_FUTURE_ROUND;
t.earningsPoolPerRound[_activationRound].setStake(_totalStake);
nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake;
emit TranscoderActivated(_transcoder, _activationRound);
}
/**
* @dev Remove a transcoder from the pool and deactivate it
*/
function resignTranscoder(address _transcoder) internal {
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPool.remove(_transcoder);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder));
uint256 deactivationRound = roundsManager().currentRound().add(1);
transcoders[_transcoder].deactivationRound = deactivationRound;
emit TranscoderDeactivated(_transcoder, deactivationRound);
}
/**
* @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.
* See SortedDoublyLL.sol for details on list hints
* @param _transcoder Address of transcoder
* @param _rewards Amount of rewards
* @param _round Round that transcoder is updated
* @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool
* @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool
*/
function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
) internal {
Transcoder storage t = transcoders[_transcoder];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];
EarningsPool.Data memory prevEarningsPool = cumulativeFactorsPool(t, t.lastRewardRound);
t.activeCumulativeRewards = t.cumulativeRewards;
uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards);
// Calculate the rewards earned by the transcoder's earned rewards
uint256 transcoderRewardStakeRewards = PreciseMathUtils.percOf(
delegatorsRewards,
t.activeCumulativeRewards,
earningsPool.totalStake
);
// Track rewards earned by the transcoder based on its earned rewards and rewardCut
t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards);
// Update cumulative reward factor with new rewards
// The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated)
// Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field
earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards);
// Update transcoder's total stake with rewards
increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext);
}
/**
* @dev Update a delegator with token pools shares from its lastClaimRound through a given round
* @param _delegator Delegator address
* @param _endRound The last round for which to update a delegator's stake with earnings pool shares
* @param _lastClaimRound The round for which a delegator has last claimed earnings
*/
function updateDelegatorWithEarnings(
address _delegator,
uint256 _endRound,
uint256 _lastClaimRound
) internal {
Delegator storage del = delegators[_delegator];
uint256 startRound = _lastClaimRound.add(1);
uint256 currentBondedAmount = del.bondedAmount;
uint256 currentFees = del.fees;
// Only will have earnings to claim if you have a delegate
// If not delegated, skip the earnings claim process
if (del.delegateAddress != address(0)) {
(currentBondedAmount, currentFees) = pendingStakeAndFees(_delegator, _endRound);
// Check whether the endEarningsPool is initialised
// If it is not initialised set it's cumulative factors so that they can be used when a delegator
// next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress];
EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound];
if (endEarningsPool.cumulativeRewardFactor == 0) {
uint256 lastRewardRound = t.lastRewardRound;
if (lastRewardRound < _endRound) {
endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound)
.cumulativeRewardFactor;
}
}
if (endEarningsPool.cumulativeFeeFactor == 0) {
uint256 lastFeeRound = t.lastFeeRound;
if (lastFeeRound < _endRound) {
endEarningsPool.cumulativeFeeFactor = cumulativeFactorsPool(t, lastFeeRound).cumulativeFeeFactor;
}
}
if (del.delegateAddress == _delegator) {
t.cumulativeFees = 0;
t.cumulativeRewards = 0;
// activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards
}
}
emit EarningsClaimed(
del.delegateAddress,
_delegator,
currentBondedAmount.sub(del.bondedAmount),
currentFees.sub(del.fees),
startRound,
_endRound
);
del.lastClaimRound = _endRound;
// Rewards are bonded by default
del.bondedAmount = currentBondedAmount;
del.fees = currentFees;
}
/**
* @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional
* list hint if needed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool
*/
function processRebond(
address _delegator,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
) internal {
Delegator storage del = delegators[_delegator];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID");
uint256 amount = lock.amount;
// Increase delegator's bonded amount
del.bondedAmount = del.bondedAmount.add(amount);
// Delete lock
delete del.unbondingLocks[_unbondingLockId];
increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext);
emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount);
}
/**
* @dev Return LivepeerToken interface
* @return Livepeer token contract registered with Controller
*/
function livepeerToken() internal view returns (ILivepeerToken) {
return ILivepeerToken(controller.getContract(keccak256("LivepeerToken")));
}
/**
* @dev Return Minter interface
* @return Minter contract registered with Controller
*/
function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
/**
* @dev Return RoundsManager interface
* @return RoundsManager contract registered with Controller
*/
function roundsManager() internal view returns (IRoundsManager) {
return IRoundsManager(controller.getContract(keccak256("RoundsManager")));
}
function _onlyTicketBroker() internal view {
require(msg.sender == controller.getContract(keccak256("TicketBroker")), "caller must be TicketBroker");
}
function _onlyRoundsManager() internal view {
require(msg.sender == controller.getContract(keccak256("RoundsManager")), "caller must be RoundsManager");
}
function _onlyVerifier() internal view {
require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier");
}
function _currentRoundInitialized() internal view {
require(roundsManager().currentRoundInitialized(), "current round is not initialized");
}
function _autoClaimEarnings() internal {
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound);
}
}
}
| * @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position. In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints @param _amount Amount of tokens to unbond @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool @param _newPosNext Address of next transcoder in pool if the caller remains in the pool/ Create new unbonding lock Increment ID for next unbonding lock Decrease delegator's bonded amount Delegator no longer delegated to anyone if it does not have a bonded amount Delegator does not have a start round if it is no longer delegated to anyone | function unbondWithHint(
uint256 _amount,
address _newPosPrev,
address _newPosNext
) public whenSystemNotPaused currentRoundInitialized autoClaimEarnings {
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
del.nextUnbondingLockId = unbondingLockId.add(1);
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
del.delegateAddress = address(0);
del.startRound = 0;
if (transcoderPool.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
| 13,004,550 | [
1,
984,
26425,
392,
3844,
434,
326,
11158,
639,
1807,
324,
265,
785,
384,
911,
471,
4533,
326,
906,
3396,
2845,
1450,
392,
3129,
666,
7380,
309,
3577,
225,
971,
326,
4894,
22632,
316,
326,
906,
3396,
2845,
16,
326,
4894,
848,
5615,
392,
3129,
7380,
364,
2097,
12626,
1754,
316,
326,
2845,
3970,
326,
1375,
67,
2704,
1616,
9958,
68,
471,
1375,
67,
2704,
1616,
2134,
68,
859,
18,
432,
9103,
1623,
903,
506,
7120,
5023,
622,
326,
7380,
358,
1104,
326,
3434,
1754,
18,
657,
326,
3796,
648,
16,
326,
7380,
353,
326,
3434,
1754,
1427,
1158,
1623,
353,
7120,
18,
2164,
13717,
3244,
440,
93,
4503,
18,
18281,
3189,
603,
666,
13442,
225,
389,
8949,
16811,
434,
2430,
358,
640,
26425,
225,
389,
2704,
1616,
9958,
5267,
434,
2416,
906,
3396,
316,
2845,
309,
326,
4894,
22632,
316,
326,
2845,
225,
389,
2704,
1616,
2134,
5267,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
640,
26425,
1190,
7002,
12,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1758,
389,
2704,
1616,
9958,
16,
203,
3639,
1758,
389,
2704,
1616,
2134,
203,
565,
262,
1071,
1347,
3163,
1248,
28590,
783,
11066,
11459,
3656,
9762,
41,
1303,
899,
288,
203,
3639,
2583,
12,
3771,
1332,
639,
1482,
12,
3576,
18,
15330,
13,
422,
24117,
639,
1482,
18,
38,
265,
785,
16,
315,
16140,
1297,
506,
324,
265,
785,
8863,
203,
203,
3639,
24117,
639,
2502,
1464,
273,
11158,
3062,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
318,
26425,
3844,
1297,
506,
6802,
2353,
374,
8863,
203,
3639,
2583,
24899,
8949,
1648,
1464,
18,
18688,
785,
6275,
16,
315,
8949,
353,
6802,
2353,
324,
265,
785,
3844,
8863,
203,
203,
3639,
1758,
783,
9586,
273,
1464,
18,
22216,
1887,
31,
203,
3639,
2254,
5034,
783,
11066,
273,
21196,
1318,
7675,
2972,
11066,
5621,
203,
3639,
2254,
5034,
598,
9446,
11066,
273,
783,
11066,
18,
1289,
12,
318,
26425,
310,
5027,
1769,
203,
3639,
2254,
5034,
640,
26425,
310,
2531,
548,
273,
1464,
18,
4285,
984,
26425,
310,
2531,
548,
31,
203,
203,
3639,
1464,
18,
4285,
984,
26425,
310,
2531,
548,
273,
640,
26425,
310,
2531,
548,
18,
1289,
12,
21,
1769,
203,
3639,
1464,
18,
18688,
785,
6275,
273,
1464,
18,
18688,
785,
6275,
18,
1717,
24899,
8949,
1769,
203,
203,
3639,
309,
261,
3771,
18,
18688,
785,
6275,
422,
374,
13,
288,
203,
5411,
1464,
18,
22216,
1887,
2
] |
pragma solidity ^0.4.11;
interface CommonWallet {
function receive() external payable;
}
library StringUtils {
function concat(string _a, string _b)
internal
pure
returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
library UintStringUtils {
function toString(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);
}
}
// @title AddressUtils
// @dev Utility library of inline functions on addresses
library AddressUtils {
// Returns whether the target address is a contract
// @dev This function will return false if invoked during the constructor of a contract,
// as the code is not actually created until after the constructor finishes.
// @param addr address to check
// @return whether the target address is a contract
function isContract(address addr)
internal
view
returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// @title SafeMath256
// @dev Math operations with safety checks that throw on error
library SafeMath256 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
// @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath32 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath8 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint8 a, uint8 b) internal pure returns (uint8 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint8 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(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/// @title A facet of DragonCore that manages special access privileges.
contract DragonAccessControl
{
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Contract owner
address internal controller_;
/// @dev Contract modes
enum Mode {TEST, PRESALE, OPERATE}
/// @dev Contract state
Mode internal mode_ = Mode.TEST;
/// @dev OffChain Server accounts ('minions') addresses
/// It's used for money withdrawal and export of tokens
mapping(address => bool) internal minions_;
/// @dev Presale contract address. Can call `presale` method.
address internal presale_;
// Modifiers ---------------------------------------------------------------
/// @dev Limit execution to controller account only.
modifier controllerOnly() {
require(controller_ == msg.sender, "controller_only");
_;
}
/// @dev Limit execution to minion account only.
modifier minionOnly() {
require(minions_[msg.sender], "minion_only");
_;
}
/// @dev Limit execution to test time only.
modifier testModeOnly {
require(mode_ == Mode.TEST, "test_mode_only");
_;
}
/// @dev Limit execution to presale time only.
modifier presaleModeOnly {
require(mode_ == Mode.PRESALE, "presale_mode_only");
_;
}
/// @dev Limit execution to operate time only.
modifier operateModeOnly {
require(mode_ == Mode.OPERATE, "operate_mode_only");
_;
}
/// @dev Limit execution to presale account only.
modifier presaleOnly() {
require(msg.sender == presale_, "presale_only");
_;
}
/// @dev set state to Mode.OPERATE.
function setOperateMode()
external
controllerOnly
presaleModeOnly
{
mode_ = Mode.OPERATE;
}
/// @dev Set presale contract address. Becomes useless when presale is over.
/// @param _presale Presale contract address.
function setPresale(address _presale)
external
controllerOnly
{
presale_ = _presale;
}
/// @dev set state to Mode.PRESALE.
function setPresaleMode()
external
controllerOnly
testModeOnly
{
mode_ = Mode.PRESALE;
}
/// @dev Get controller address.
/// @return Address of contract's controller.
function controller()
external
view
returns(address)
{
return controller_;
}
/// @dev Transfer control to new address. Set controller an approvee for
/// tokens that managed by contract itself. Remove previous controller value
/// from contract's approvees.
/// @param _to New controller address.
function setController(address _to)
external
controllerOnly
{
require(_to != NA, "_to");
require(controller_ != _to, "already_controller");
controller_ = _to;
}
/// @dev Check if address is a minion.
/// @param _addr Address to check.
/// @return True if address is a minion.
function isMinion(address _addr)
public view returns(bool)
{
return minions_[_addr];
}
function getCurrentMode()
public view returns (Mode)
{
return mode_;
}
}
/// @dev token description, storage and transfer functions
contract DragonBase is DragonAccessControl
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using StringUtils for string;
using UintStringUtils for uint;
/// @dev The Birth event is fired whenever a new dragon comes into existence.
event Birth(address owner, uint256 petId, uint256 tokenId, uint256 parentA, uint256 parentB, string genes, string params);
/// @dev Token name
string internal name_;
/// @dev Token symbol
string internal symbol_;
/// @dev Token resolving url
string internal url_;
struct DragonToken {
// Constant Token params
uint8 genNum; // generation number. uses for dragon view
string genome; // genome description
uint256 petId; // offchain dragon identifier
// Parents
uint256 parentA;
uint256 parentB;
// Game-depening Token params
string params; // can change in export operation
// State
address owner;
}
/// @dev Count of minted tokens
uint256 internal mintCount_;
/// @dev Maximum token supply
uint256 internal maxSupply_;
/// @dev Count of burn tokens
uint256 internal burnCount_;
// Tokens state
/// @dev Token approvals values
mapping(uint256 => address) internal approvals_;
/// @dev Operator approvals
mapping(address => mapping(address => bool)) internal operatorApprovals_;
/// @dev Index of token in owner's token list
mapping(uint256 => uint256) internal ownerIndex_;
/// @dev Owner's tokens list
mapping(address => uint256[]) internal ownTokens_;
/// @dev Tokens
mapping(uint256 => DragonToken) internal tokens_;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Add token to new owner. Increase owner's balance.
/// @param _to Token receiver.
/// @param _tokenId New token id.
function _addTo(address _to, uint256 _tokenId)
internal
{
DragonToken storage token = tokens_[_tokenId];
require(token.owner == NA, "taken");
uint256 lastIndex = ownTokens_[_to].length;
ownTokens_[_to].push(_tokenId);
ownerIndex_[_tokenId] = lastIndex;
token.owner = _to;
}
/// @dev Create new token and increase mintCount.
/// @param _genome New token's genome.
/// @param _params Token params string.
/// @param _parentA Token A parent.
/// @param _parentB Token B parent.
/// @return New token id.
function _createToken(
address _to,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId,
string _params
)
internal returns(uint256)
{
uint256 tokenId = mintCount_.add(1);
mintCount_ = tokenId;
DragonToken memory token = DragonToken(
_genNum,
_genome,
_petId,
_parentA,
_parentB,
_params,
NA
);
tokens_[tokenId] = token;
_addTo(_to, tokenId);
emit Birth(_to, _petId, tokenId, _parentA, _parentB, _genome, _params);
return tokenId;
}
/// @dev Get token genome.
/// @param _tokenId Token id.
/// @return Token's genome.
function getGenome(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].genome;
}
/// @dev Get token params.
/// @param _tokenId Token id.
/// @return Token's params.
function getParams(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].params;
}
/// @dev Get token parentA.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentA(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentA;
}
/// @dev Get token parentB.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentB(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentB;
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function isExisting(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Receive maxium token supply value.
/// @return Contracts `maxSupply_` variable.
function maxSupply()
external view returns(uint256)
{
return maxSupply_;
}
/// @dev Set url prefix for tokenURI generation.
/// @param _url Url prefix value.
function setUrl(string _url)
external controllerOnly
{
url_ = _url;
}
/// @dev Get token symbol.
/// @return Token symbol name.
function symbol()
external view returns(string)
{
return symbol_;
}
/// @dev Get token URI to receive offchain information by it's id.
/// @param _tokenId Token id.
/// @return URL string. For example "http://erc721.tld/tokens/1".
function tokenURI(uint256 _tokenId)
external view returns(string)
{
return url_.concat(_tokenId.toString());
}
/// @dev Get token name.
/// @return Token name string.
function name()
external view returns(string)
{
return name_;
}
/// @dev return information about _owner tokens
function getTokens(address _owner)
external view returns (uint256[], uint256[], byte[])
{
uint256[] memory tokens = ownTokens_[_owner];
uint256[] memory tokenIds = new uint256[](tokens.length);
uint256[] memory petIds = new uint256[](tokens.length);
byte[] memory genomes = new byte[](tokens.length * 77);
uint index = 0;
for(uint i = 0; i < tokens.length; i++) {
uint256 tokenId = tokens[i];
DragonToken storage token = tokens_[tokenId];
tokenIds[i] = tokenId;
petIds[i] = token.petId;
bytes storage genome = bytes(token.genome);
for(uint j = 0; j < genome.length; j++) {
genomes[index++] = genome[j];
}
}
return (tokenIds, petIds, genomes);
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @dev See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721.sol
contract ERC721Basic
{
/// @dev Emitted when token approvee is set
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev Emitted when owner approve all own tokens to operator.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev Emitted when user deposit some funds.
event Deposit(address indexed _sender, uint256 _value);
/// @dev Emitted when user deposit some funds.
event Withdraw(address indexed _sender, uint256 _value);
/// @dev Emitted when token transferred to new owner
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Required methods
function balanceOf(address _owner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function getApproved(uint256 _tokenId) public view returns (address _to);
//function transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic
{
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver
{
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data )
public returns(bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Metadata, ERC721Receiver
{
/// @dev Interface signature 721 for interface detection.
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
}
/// @dev ERC721 methods
contract DragonOwnership is ERC721, DragonBase
{
using StringUtils for string;
using UintStringUtils for uint;
using AddressUtils for address;
/// @dev Emitted when token transferred to new owner. Additional fields is petId, genes, params
/// it uses for client-side indication
event TransferInfo(address indexed _from, address indexed _to, uint256 _tokenId, uint256 petId, string genes, string params);
/// @dev Specify if _addr is token owner or approvee. Also check if `_addr`
/// is operator for token owner.
/// @param _tokenId Token to check ownership of.
/// @param _addr Address to check if it's an owner or an aprovee of `_tokenId`.
/// @return True if token can be managed by provided `_addr`.
function isOwnerOrApproved(uint256 _tokenId, address _addr)
public view returns(bool)
{
DragonToken memory token = tokens_[_tokenId];
if (token.owner == _addr) {
return true;
}
else if (isApprovedFor(_tokenId, _addr)) {
return true;
}
else if (isApprovedForAll(token.owner, _addr)) {
return true;
}
return false;
}
/// @dev Limit execution to token owner or approvee only.
/// @param _tokenId Token to check ownership of.
modifier ownerOrApprovedOnly(uint256 _tokenId) {
require(isOwnerOrApproved(_tokenId, msg.sender), "tokenOwnerOrApproved_only");
_;
}
/// @dev Contract's own token only acceptable.
/// @param _tokenId Contract's token id.
modifier ownOnly(uint256 _tokenId) {
require(tokens_[_tokenId].owner == address(this), "own_only");
_;
}
/// @dev Determine if token is approved for specified approvee.
/// @param _tokenId Target token id.
/// @param _approvee Approvee address.
/// @return True if so.
function isApprovedFor(uint256 _tokenId, address _approvee)
public view returns(bool)
{
return approvals_[_tokenId] == _approvee;
}
/// @dev Specify is given address set as operator with setApprovalForAll.
/// @param _owner Token owner.
/// @param _operator Address to check if it an operator.
/// @return True if operator is set.
function isApprovedForAll(address _owner, address _operator)
public view returns(bool)
{
return operatorApprovals_[_owner][_operator];
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function exists(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Get owner of a token.
/// @param _tokenId Token owner id.
/// @return Token owner address.
function ownerOf(uint256 _tokenId)
public view returns(address)
{
return tokens_[_tokenId].owner;
}
/// @dev Get approvee address. If there is not approvee returns 0x0.
/// @param _tokenId Token id to get approvee of.
/// @return Approvee address or 0x0.
function getApproved(uint256 _tokenId)
public view returns(address)
{
return approvals_[_tokenId];
}
/// @dev Grant owner alike controll permissions to third party.
/// @param _to Permission receiver.
/// @param _tokenId Granted token id.
function approve(address _to, uint256 _tokenId)
external ownerOrApprovedOnly(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != NA || _to != NA) {
approvals_[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/// @dev Current total tokens supply. Always less then maxSupply.
/// @return Difference between minted and burned tokens.
function totalSupply()
public view returns(uint256)
{
return mintCount_;
}
/// @dev Get number of tokens which `_owner` owns.
/// @param _owner Address to count own tokens.
/// @return Count of owned tokens.
function balanceOf(address _owner)
external view returns(uint256)
{
return ownTokens_[_owner].length;
}
/// @dev Internal set approval for all without _owner check.
/// @param _owner Granting user.
/// @param _to New account approvee.
/// @param _approved Set new approvee status.
function _setApprovalForAll(address _owner, address _to, bool _approved)
internal
{
operatorApprovals_[_owner][_to] = _approved;
emit ApprovalForAll(_owner, _to, _approved);
}
/// @dev Set approval for all account tokens.
/// @param _to Approvee address.
/// @param _approved Value true or false.
function setApprovalForAll(address _to, bool _approved)
external
{
require(_to != msg.sender);
_setApprovalForAll(msg.sender, _to, _approved);
}
/// @dev Remove approval bindings for token. Do nothing if no approval
/// exists.
/// @param _from Address of token owner.
/// @param _tokenId Target token id.
function _clearApproval(address _from, uint256 _tokenId)
internal
{
if (approvals_[_tokenId] == NA) {
return;
}
approvals_[_tokenId] = NA;
emit Approval(_from, NA, _tokenId);
}
/// @dev Check if contract was received by other side properly if receiver
/// is a ctontract.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
/// @return True on success.
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal returns(bool)
{
if (! _to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
/// @dev Remove token from owner. Unrecoverable.
/// @param _tokenId Removing token id.
function _remove(uint256 _tokenId)
internal
{
address owner = tokens_[_tokenId].owner;
_removeFrom(owner, _tokenId);
}
/// @dev Completely remove token from the contract. Unrecoverable.
/// @param _owner Owner of removing token.
/// @param _tokenId Removing token id.
function _removeFrom(address _owner, uint256 _tokenId)
internal
{
uint256 lastIndex = ownTokens_[_owner].length.sub(1);
uint256 lastToken = ownTokens_[_owner][lastIndex];
// Swap users token
ownTokens_[_owner][ownerIndex_[_tokenId]] = lastToken;
ownTokens_[_owner].length--;
// Swap token indexes
ownerIndex_[lastToken] = ownerIndex_[_tokenId];
ownerIndex_[_tokenId] = 0;
DragonToken storage token = tokens_[_tokenId];
token.owner = NA;
}
/// @dev Transfer token from owner `_from` to another address or contract
/// `_to` by it's `_tokenId`.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function transferFrom( address _from, address _to, uint256 _tokenId )
public ownerOrApprovedOnly(_tokenId)
{
require(_from != NA);
require(_to != NA);
_clearApproval(_from, _tokenId);
_removeFrom(_from, _tokenId);
_addTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
DragonToken storage token = tokens_[_tokenId];
emit TransferInfo(_from, _to, _tokenId, token.petId, token.genome, token.params);
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params
)
public
{
updateAndSafeTransferFrom(_to, _tokenId, _params, "");
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token and send
/// protion of _data to it.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
/// @param _data Notification data.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params,
bytes _data
)
public
{
// Safe transfer from
updateAndTransferFrom(_to, _tokenId, _params, 0, 0);
require(_checkAndCallSafeTransfer(address(this), _to, _tokenId, _data));
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndTransferFrom(
address _to,
uint256 _tokenId,
string _params,
uint256 _petId,
uint256 _transferCost
)
public
ownOnly(_tokenId)
minionOnly
{
require(bytes(_params).length > 0, "params_length");
// Update
tokens_[_tokenId].params = _params;
if (tokens_[_tokenId].petId == 0 ) {
tokens_[_tokenId].petId = _petId;
}
address from = tokens_[_tokenId].owner;
// Transfer from
transferFrom(from, _to, _tokenId);
// send to the server's wallet the transaction cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/// @dev Burn owned token. Increases `burnCount_` and decrease `totalSupply`
/// value.
/// @param _tokenId Id of burning token.
function burn(uint256 _tokenId)
public
ownerOrApprovedOnly(_tokenId)
{
address owner = tokens_[_tokenId].owner;
_remove(_tokenId);
burnCount_ += 1;
emit Transfer(owner, NA, _tokenId);
}
/// @dev Receive count of burned tokens. Should be greater than `totalSupply`
/// but less than `mintCount`.
/// @return Number of burned tokens
function burnCount()
external
view
returns(uint256)
{
return burnCount_;
}
function onERC721Received(address, uint256, bytes)
public returns(bytes4)
{
return ERC721_RECEIVED;
}
}
/// @title Managing contract. implements the logic of buying tokens, depositing / withdrawing funds
/// to the project account and importing / exporting tokens
contract EtherDragonsCore is DragonOwnership
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using AddressUtils for address;
using StringUtils for string;
using UintStringUtils for uint;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Bounty tokens count limit
uint256 public constant BOUNTY_LIMIT = 2500;
/// @dev Presale tokens count limit
uint256 public constant PRESALE_LIMIT = 7500;
///@dev Total gen0tokens generation limit
uint256 public constant GEN0_CREATION_LIMIT = 90000;
/// @dev Number of tokens minted in presale stage
uint256 internal presaleCount_;
/// @dev Number of tokens minted for bounty campaign
uint256 internal bountyCount_;
///@dev Company bank address
address internal bank_;
// Extension ---------------------------------------------------------------
/// @dev Contract is not payable. To fullfil balance method `depositTo`
/// should be used.
function ()
public payable
{
revert();
}
/// @dev amount on the account of the contract. This amount consists of deposits from players and the system reserve for payment of transactions
/// the player at any time to withdraw the amount corresponding to his account in the game, minus the cost of the transaction
function getBalance()
public view returns (uint256)
{
return address(this).balance;
}
/// @dev at the moment of creation of the contract we transfer the address of the bank
/// presell contract address set later
constructor(
address _bank
)
public
{
require(_bank != NA);
controller_ = msg.sender;
bank_ = _bank;
// Meta
name_ = "EtherDragons";
symbol_ = "ED";
url_ = "https://game.etherdragons.world/token/";
// Token mint limit
maxSupply_ = GEN0_CREATION_LIMIT + BOUNTY_LIMIT + PRESALE_LIMIT;
}
/// Number of tokens minted in presale stage
function totalPresaleCount()
public view returns(uint256)
{
return presaleCount_;
}
/// @dev Number of tokens minted for bounty campaign
function totalBountyCount()
public view returns(uint256)
{
return bountyCount_;
}
/// @dev Check if new token could be minted. Return true if count of minted
/// tokens less than could be minted through contract deploy.
/// Also, tokens can not be created more often than once in mintDelay_ minutes
/// @return True if current count is less then maximum tokens available for now.
function canMint()
public view returns(bool)
{
return (mintCount_ + presaleCount_ + bountyCount_) < maxSupply_;
}
/// @dev Here we write the addresses of the wallets of the server from which it is accessed
/// to contract methods.
/// @param _to New minion address
function minionAdd(address _to)
external controllerOnly
{
require(minions_[_to] == false, "already_minion");
// ΡΠ°Π·ΡΠ΅ΡΠ°Π΅ΠΌ ΡΡΠΎΠΌΡ Π°Π΄ΡΠ΅ΡΡ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡΡΡ ΡΠΎΠΊΠ΅Π½Π°ΠΌΠΈ ΠΊΠΎΠ½ΡΠ°ΠΊΡΠ°
// allow the address to use contract tokens
_setApprovalForAll(address(this), _to, true);
minions_[_to] = true;
}
/// @dev delete the address of the server wallet
/// @param _to Minion address
function minionRemove(address _to)
external controllerOnly
{
require(minions_[_to], "not_a_minion");
// and forbid this wallet to use tokens of the contract
_setApprovalForAll(address(this), _to, false);
minions_[_to] = false;
}
/// @dev Here the player can put funds to the account of the contract
/// and get the same amount of in-game currency
/// the game server understands who puts money at the wallet address
function depositTo()
public payable
{
emit Deposit(msg.sender, msg.value);
}
/// @dev Transfer amount of Ethers to specified receiver. Only owner can
// call this method.
/// @param _to Transfer receiver.
/// @param _amount Transfer value.
/// @param _transferCost Transfer cost.
function transferAmount(address _to, uint256 _amount, uint256 _transferCost)
external minionOnly
{
require((_amount + _transferCost) <= address(this).balance, "not enough money!");
_to.transfer(_amount);
// send to the wallet of the server the transfer cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
emit Withdraw(_to, _amount);
}
/// @dev Mint new token with specified params. Transfer `_fee` to the
/// `bank`.
/// @param _to New token owner.
/// @param _fee Transaction fee.
/// @param _genNum Generation number..
/// @param _genome New genome unique value.
/// @param _parentA Parent A.
/// @param _parentB Parent B.
/// @param _petId Pet identifier.
/// @param _params List of parameters for pet.
/// @param _transferCost Transfer cost.
/// @return New token id.
function mintRelease(
address _to,
uint256 _fee,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId, //if petID = 0, then it was created outside of the server
string _params,
uint256 _transferCost
)
external minionOnly operateModeOnly returns(uint256)
{
require(canMint(), "can_mint");
require(_to != NA, "_to");
require((_fee + _transferCost) <= address(this).balance, "_fee");
require(bytes(_params).length != 0, "params_length");
require(bytes(_genome).length == 77, "genome_length");
// Parents should be both 0 or both not.
if (_parentA != 0 && _parentB != 0) {
require(_parentA != _parentB, "same_parent");
}
else if (_parentA == 0 && _parentB != 0) {
revert("parentA_empty");
}
else if (_parentB == 0 && _parentA != 0) {
revert("parentB_empty");
}
uint256 tokenId = _createToken(_to, _genNum, _genome, _parentA, _parentB, _petId, _params);
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
// Transfer mint fee to the fund
CommonWallet(bank_).receive.value(_fee)();
emit Transfer(NA, _to, tokenId);
// send to the server wallet server the transfer cost,
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
return tokenId;
}
/// @dev Create new token via presale state
/// @param _to New token owner.
/// @param _genome New genome unique value.
/// @return New token id.
/// at the pre-sale stage we sell the zero-generation pets, which have only a genome.
/// other attributes of such a token get when importing to the server
function mintPresell(address _to, string _genome)
external presaleOnly presaleModeOnly returns(uint256)
{
require(presaleCount_ < PRESALE_LIMIT, "presale_limit");
// Ρ ΠΏΡΠ΅ΡΠ΅ΠΉΠ» ΠΏΠ΅ΡΠ° Π½Π΅Ρ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΠΎΠ². ΠΡ
ΠΎΠ½ ΠΏΠΎΠ»ΡΡΠΈΡ ΠΏΠΎΡΠ»Π΅ Π²Π²ΠΎΠ΄Π° Π² ΠΈΠ³ΡΡ.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
presaleCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
/// @dev Create new token for bounty activity
/// @param _to New token owner.
/// @return New token id.
function mintBounty(address _to, string _genome)
external controllerOnly returns(uint256)
{
require(bountyCount_ < BOUNTY_LIMIT, "bounty_limit");
// bounty pet has no parameters. They will receive them after importing to the game.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
bountyCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
}
contract Presale
{
// Extension ---------------------------------------------------------------
using AddressUtils for address;
// Events ------------------------------------------------------------------
///the event is fired when starting a new wave presale stage
event StageBegin(uint8 stage, uint256 timestamp);
///the event is fired when token sold
event TokensBought(address buyerAddr, uint256[] tokenIds, bytes genomes);
// Types -------------------------------------------------------------------
struct Stage {
// Predefined values
uint256 price; // token's price on the stage
uint16 softcap; // stage softCap
uint16 hardcap; // stage hardCap
// Unknown values
uint16 bought; // sold on stage
uint32 startDate; // stage's beginDate
uint32 endDate; // stage's endDate
}
// Constants ---------------------------------------------------------------
// 10 stages of 5 genocodes
uint8 public constant STAGES = 10;
uint8 internal constant TOKENS_PER_STAGE = 5;
address constant NA = address(0);
// State -------------------------------------------------------------------
address internal CEOAddress; // contract owner
address internal bank_; // profit wallet address (not a contract)
address internal erc721_; // main contract address
/// @dev genomes for bounty stage
string[TOKENS_PER_STAGE][STAGES] internal genomes_;
/// stages data
Stage[STAGES] internal stages_;
// internal transaction counter, it uses for random generator
uint32 internal counter_;
/// stage is over
bool internal isOver_;
/// stage number
uint8 internal stageIndex_;
/// stage start Data
uint32 internal stageStart_;
// Lifetime ----------------------------------------------------------------
constructor(
address _bank,
address _erc721
)
public
{
require(_bank != NA, '_bank');
require(_erc721.isContract(), '_erc721');
CEOAddress = msg.sender;
// Addresses should not be the same.
require(_bank != CEOAddress, "bank = CEO");
require(CEOAddress != _erc721, "CEO = erc721");
require(_erc721 != _bank, "bank = erc721");
// Update state
bank_ = _bank;
erc721_ = _erc721;
// stages data
stages_[0].price = 10 finney;
stages_[0].softcap = 100;
stages_[0].hardcap = 300;
stages_[1].price = 20 finney;
stages_[1].softcap = 156;
stages_[1].hardcap = 400;
stages_[2].price = 32 finney;
stages_[2].softcap = 212;
stages_[2].hardcap = 500;
stages_[3].price = 45 finney;
stages_[3].softcap = 268;
stages_[3].hardcap = 600;
stages_[4].price = 58 finney;
stages_[4].softcap = 324;
stages_[4].hardcap = 700;
stages_[5].price = 73 finney;
stages_[5].softcap = 380;
stages_[5].hardcap = 800;
stages_[6].price = 87 finney;
stages_[6].softcap = 436;
stages_[6].hardcap = 900;
stages_[7].price = 102 finney;
stages_[7].softcap = 492;
stages_[7].hardcap = 1000;
stages_[8].price = 118 finney;
stages_[8].softcap = 548;
stages_[8].hardcap = 1100;
stages_[9].price = 129 finney;
stages_[9].softcap = 604;
stages_[9].hardcap = 1200;
}
/// fill the genomes data
function setStageGenomes(
uint8 _stage,
string _genome0,
string _genome1,
string _genome2,
string _genome3,
string _genome4
)
external controllerOnly
{
genomes_[_stage][0] = _genome0;
genomes_[_stage][1] = _genome1;
genomes_[_stage][2] = _genome2;
genomes_[_stage][3] = _genome3;
genomes_[_stage][4] = _genome4;
}
/// @dev Contract itself is non payable
function ()
public payable
{
revert();
}
// Modifiers ---------------------------------------------------------------
/// only from contract owner
modifier controllerOnly() {
require(msg.sender == CEOAddress, 'controller_only');
_;
}
/// only for active stage
modifier notOverOnly() {
require(isOver_ == false, 'notOver_only');
_;
}
// Getters -----------------------------------------------------------------
/// owner address
function getCEOAddress()
public view returns(address)
{
return CEOAddress;
}
/// counter from random number generator
function counter()
internal view returns(uint32)
{
return counter_;
}
// tokens sold by stage ...
function stageTokensBought(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].bought;
}
// stage softcap
function stageSoftcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].softcap;
}
/// stage hardcap
function stageHardcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].hardcap;
}
/// stage Start Date
function stageStartDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].startDate;
}
/// stage Finish Date
function stageEndDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].endDate;
}
/// stage token price
function stagePrice(uint _stage)
public view returns(uint)
{
return stages_[_stage].price;
}
// Genome Logic -----------------------------------------------------------------
/// within the prelase , the dragons are generated, which are the ancestors of the destiny
/// newborns have a high chance of mutation and are unlikely to be purebred
/// the player will have to collect the breed, crossing a lot of pets
/// In addition, you will need to pick up combat abilities
/// these characteristics are assigned to the pet when the dragon is imported to the game server.
function nextGenome()
internal returns(string)
{
uint8 n = getPseudoRandomNumber();
counter_ += 1;
return genomes_[stageIndex_][n];
}
function getPseudoRandomNumber()
internal view returns(uint8 index)
{
uint8 n = uint8(
keccak256(abi.encode(msg.sender, block.timestamp + counter_))
);
return n % TOKENS_PER_STAGE;
}
// PreSale Logic -----------------------------------------------------------------
/// Presale stage0 begin date set
/// presale start is possible only once
function setStartDate(uint32 _startDate)
external controllerOnly
{
require(stages_[0].startDate == 0, 'already_set');
stages_[0].startDate = _startDate;
stageStart_ = _startDate;
stageIndex_ = 0;
emit StageBegin(stageIndex_, stageStart_);
}
/// current stage number
/// switches to the next stage if the time has come
function stageIndex()
external view returns(uint8)
{
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now) {
return stageIndex_ + 1;
}
else {
return stageIndex_;
}
}
/// check whether the phase started
/// switch to the next stage, if necessary
function beforeBuy()
internal
{
if (stageStart_ == 0) {
revert('presale_not_started');
}
else if (stageStart_ > now) {
revert('stage_not_started');
}
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now)
{
stageIndex_ += 1;
stageStart_ = stages_[stageIndex_].startDate;
if (stageStart_ > now) {
revert('stage_not_started');
}
}
}
/// time to next midnight
function midnight()
public view returns(uint32)
{
uint32 tomorrow = uint32(now + 1 days);
uint32 remain = uint32(tomorrow % 1 days);
return tomorrow - remain;
}
/// buying a specified number of tokens
function buyTokens(uint16 numToBuy)
public payable notOverOnly returns(uint256[])
{
beforeBuy();
require(numToBuy > 0 && numToBuy <= 10, "numToBuy error");
Stage storage stage = stages_[stageIndex_];
require((stage.price * numToBuy) <= msg.value, 'price');
uint16 prevBought = stage.bought;
require(prevBought + numToBuy <= stage.hardcap, "have required tokens");
stage.bought += numToBuy;
uint256[] memory tokenIds = new uint256[](numToBuy);
bytes memory genomes = new bytes(numToBuy * 77);
uint32 genomeByteIndex = 0;
for(uint16 t = 0; t < numToBuy; t++)
{
string memory genome = nextGenome();
uint256 tokenId = EtherDragonsCore(erc721_).mintPresell(msg.sender, genome);
bytes memory genomeBytes = bytes(genome);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[genomeByteIndex++] = genomeBytes[gi];
}
tokenIds[t] = tokenId;
}
// Transfer mint fee to the fund
bank_.transfer(address(this).balance);
if (stage.bought == stage.hardcap) {
stage.endDate = uint32(now);
stageStart_ = midnight() + 1 days + 1 seconds;
if (stageIndex_ < STAGES - 1) {
stageIndex_ += 1;
}
else {
isOver_ = true;
}
}
else if (stage.bought >= stage.softcap && prevBought < stage.softcap) {
stage.endDate = midnight() + 1 days;
if (stageIndex_ < STAGES - 1) {
stages_[stageIndex_ + 1].startDate = stage.endDate + 1 days;
}
}
emit TokensBought(msg.sender, tokenIds, genomes);
return tokenIds;
}
function currTime()
public view returns(uint)
{
return now;
}
/// stages data
function getStagesInfo()
public view returns (uint256[] prices, uint16[] softcaps, uint16[] hardcaps, uint16[] boughts)
{
prices = new uint256[](STAGES);
softcaps = new uint16[](STAGES);
hardcaps = new uint16[](STAGES);
boughts = new uint16[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
prices[s] = stages_[s].price;
softcaps[s] = stages_[s].softcap;
hardcaps[s] = stages_[s].hardcap;
boughts[s] = stages_[s].bought;
}
}
/// stages dates data
function getStagesBeginEnd()
public view returns (uint32[] startDates, uint32[] endDates)
{
startDates = new uint32[](STAGES);
endDates = new uint32[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
startDates[s] = stages_[s].startDate;
endDates[s] = stages_[s].endDate;
}
}
/// returns data which genomes can be purchased at the stage
function stageGenomes(uint8 _stage)
public view returns(byte[])
{
byte[] memory genomes = new byte[](uint16(TOKENS_PER_STAGE) * 77);
uint32 gbIndex = 0;
for(uint8 tokenIndex = 0; tokenIndex < TOKENS_PER_STAGE; tokenIndex++) {
bytes memory genomeBytes = bytes(genomes_[_stage][tokenIndex]);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[gbIndex++] = genomeBytes[gi];
}
}
return genomes;
}
} | @dev Mint new token with specified params. Transfer `_fee` to the `bank`. @param _to New token owner. @param _fee Transaction fee. @param _genNum Generation number.. @param _genome New genome unique value. @param _parentA Parent A. @param _parentB Parent B. @param _petId Pet identifier. @param _params List of parameters for pet. @param _transferCost Transfer cost. @return New token id. Constant Token params Game-depening Token params Parents should be both 0 or both not. send to the server wallet server the transfer cost, withdraw it from the balance of the contract. this amount must be withdrawn from the player on the side of the game server | function mintRelease(
address _to,
uint256 _fee,
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
string _params,
uint256 _transferCost
)
external minionOnly operateModeOnly returns(uint256)
{
require(canMint(), "can_mint");
require(_to != NA, "_to");
require((_fee + _transferCost) <= address(this).balance, "_fee");
require(bytes(_params).length != 0, "params_length");
require(bytes(_genome).length == 77, "genome_length");
if (_parentA != 0 && _parentB != 0) {
require(_parentA != _parentB, "same_parent");
}
else if (_parentA == 0 && _parentB != 0) {
revert("parentA_empty");
}
else if (_parentB == 0 && _parentA != 0) {
revert("parentB_empty");
}
uint256 tokenId = _createToken(_to, _genNum, _genome, _parentA, _parentB, _petId, _params);
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
return tokenId;
}
| 5,397,235 | [
1,
49,
474,
394,
1147,
598,
1269,
859,
18,
12279,
1375,
67,
21386,
68,
358,
326,
1375,
10546,
8338,
225,
389,
869,
1166,
1147,
3410,
18,
225,
389,
21386,
5947,
14036,
18,
225,
389,
4507,
2578,
23234,
1300,
838,
225,
389,
23220,
1166,
14696,
3089,
460,
18,
225,
389,
2938,
37,
9520,
432,
18,
225,
389,
2938,
38,
9520,
605,
18,
225,
389,
6951,
548,
453,
278,
2756,
18,
225,
389,
2010,
987,
434,
1472,
364,
293,
278,
18,
225,
389,
13866,
8018,
12279,
6991,
18,
327,
1166,
1147,
612,
18,
10551,
3155,
859,
14121,
17,
323,
1907,
310,
3155,
859,
9520,
87,
1410,
506,
3937,
374,
578,
3937,
486,
18,
1366,
358,
326,
1438,
9230,
1438,
326,
7412,
6991,
16,
598,
9446,
518,
628,
326,
11013,
434,
326,
6835,
18,
333,
3844,
1297,
506,
598,
9446,
82,
628,
326,
7291,
603,
326,
4889,
434,
326,
7920,
1438,
2,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | [
1,
565,
445,
312,
474,
7391,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
21386,
16,
203,
540,
203,
3639,
2254,
28,
282,
389,
4507,
2578,
16,
203,
3639,
533,
282,
389,
23220,
16,
203,
3639,
2254,
5034,
389,
2938,
37,
16,
203,
3639,
2254,
5034,
389,
2938,
38,
16,
203,
540,
203,
3639,
533,
282,
389,
2010,
16,
203,
3639,
2254,
5034,
389,
13866,
8018,
203,
565,
262,
203,
3639,
3903,
13524,
3386,
20829,
2309,
3386,
1135,
12,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
4169,
49,
474,
9334,
315,
4169,
67,
81,
474,
8863,
203,
3639,
2583,
24899,
869,
480,
28182,
16,
4192,
869,
8863,
203,
3639,
2583,
12443,
67,
21386,
397,
389,
13866,
8018,
13,
1648,
1758,
12,
2211,
2934,
12296,
16,
4192,
21386,
8863,
203,
3639,
2583,
12,
3890,
24899,
2010,
2934,
2469,
480,
374,
16,
315,
2010,
67,
2469,
8863,
203,
3639,
2583,
12,
3890,
24899,
23220,
2934,
2469,
422,
28244,
16,
315,
23220,
67,
2469,
8863,
203,
540,
203,
3639,
309,
261,
67,
2938,
37,
480,
374,
597,
389,
2938,
38,
480,
374,
13,
288,
203,
5411,
2583,
24899,
2938,
37,
480,
389,
2938,
38,
16,
315,
14307,
67,
2938,
8863,
203,
3639,
289,
203,
3639,
469,
309,
261,
67,
2938,
37,
422,
374,
597,
389,
2938,
38,
480,
374,
13,
288,
203,
5411,
15226,
2932,
2938,
37,
67,
5531,
8863,
203,
3639,
289,
203,
3639,
469,
309,
261,
67,
2938,
38,
422,
374,
597,
389,
2938,
37,
480,
374,
13,
288,
2
] |
./full_match/1/0x47a4A4637ac574C797a06F18840dd26391Bb0d1E/sources/Astroape.sol | Contract implementation Tax and charity fees will start at 0 so we don't have a big impact when deploying to Uniswap Charity wallet address is null but the method to set the address is exposed We will set a minimum amount of tokens to be swaped => 5M | contract AstroApe is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'ASTROAPE';
string private _symbol = 'AAPE';
uint8 private _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _charityFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousCharityFee = _charityFee;
address payable public _charityWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 100000000000000 * 10**9;
uint256 private _numOfTokensToExchangeForCharity = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable charityWalletAddress, address payable marketingWalletAddress) public {
_charityWalletAddress = charityWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _charityFee == 0) return;
_previousTaxFee = _taxFee;
_previousCharityFee = _charityFee;
_taxFee = 0;
_charityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_charityFee = _previousCharityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
bool takeFee = true;
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
_tokenTransfer(sender,recipient,amount,takeFee);
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function sendETHToCharity(uint256 amount) private {
_charityWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToCharity(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeCharity(uint256 tCharity) private {
uint256 currentRate = _getRate();
uint256 rCharity = tCharity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rCharity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tCharity);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getTValues(tAmount, _taxFee, _charityFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tCharity);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 charityFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tCharity = tAmount.mul(charityFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tCharity);
return (tTransferAmount, tFee, tCharity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10');
_taxFee = taxFee;
}
function _setCharityFee(uint256 charityFee) external onlyOwner() {
require(charityFee >= 1 && charityFee <= 11, 'charityFee should be in 1 - 11');
_charityFee = charityFee;
}
function _setCharityWallet(address payable charityWalletAddress) external onlyOwner() {
_charityWalletAddress = charityWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
} | 9,613,347 | [
1,
8924,
4471,
18240,
471,
1149,
560,
1656,
281,
903,
787,
622,
374,
1427,
732,
2727,
1404,
1240,
279,
5446,
15800,
1347,
7286,
310,
358,
1351,
291,
91,
438,
3703,
560,
9230,
1758,
353,
446,
1496,
326,
707,
358,
444,
326,
1758,
353,
16265,
1660,
903,
444,
279,
5224,
3844,
434,
2430,
358,
506,
1352,
5994,
516,
1381,
49,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
6835,
16614,
303,
37,
347,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
3639,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
3639,
1450,
5267,
364,
1758,
31,
203,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
3639,
1758,
8526,
3238,
389,
24602,
31,
203,
377,
203,
3639,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
3639,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
3639,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
3639,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
3639,
533,
3238,
389,
529,
273,
296,
9053,
1457,
37,
1423,
13506,
203,
3639,
533,
3238,
389,
7175,
273,
296,
5284,
1423,
13506,
203,
3639,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
540,
203,
3639,
2254,
5034,
3238,
389,
8066,
14667,
273,
576,
31,
7010,
3639,
2254,
5034,
3238,
389,
3001,
560,
14667,
273,
1728,
31,
203,
3639,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/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 {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.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";
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 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 "./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.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.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/ISwap.sol";
/**
* @title Liquidity Provider Token
* @notice This token is an ERC20 detailed token with added capability to be minted by the owner.
* It is used to represent user's shares when providing liquidity to swap contracts.
* @dev Only Swap contracts should initialize and own LPToken contracts.
*/
contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
/**
* @notice Initializes this LPToken contract with the given name and symbol
* @dev The caller of this function will become the owner. A Swap contract should call this
* in its initializer function.
* @param name name of this token
* @param symbol symbol of this token
*/
function initialize(string memory name, string memory symbol)
external
initializer
returns (bool)
{
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__Ownable_init_unchained();
return true;
}
/**
* @notice Mints the given amount of LPToken to the recipient.
* @dev only owner can call this mint function
* @param recipient address of account to receive the tokens
* @param amount amount of tokens to mint
*/
function mint(address recipient, uint256 amount) external onlyOwner {
require(amount != 0, "LPToken: cannot mint 0");
_mint(recipient, amount);
}
/**
* @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including
* minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime.
* This assumes the owner is set to a Swap contract's address.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "LPToken: cannot send to itself");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IAllowlist {
function getPoolAccountLimit(address poolAddress)
external
view
returns (uint256);
function getPoolCap(address poolAddress) external view returns (uint256);
function verifyAddress(address account, bytes32[] calldata merkleProof)
external
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface IMetaSwap {
// pool data view functions
function getA() external view returns (uint256);
function getToken(uint8 index) external view returns (IERC20);
function getTokenIndex(address tokenAddress) external view returns (uint8);
function getTokenBalance(uint8 index) external view returns (uint256);
function getVirtualPrice() external view returns (uint256);
function isGuarded() external view returns (bool);
// min return calculation functions
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256);
function calculateSwapUnderlying(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256);
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256);
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount);
// state modifying functions
function initialize(
IERC20[] memory pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 a,
uint256 fee,
uint256 adminFee
) external;
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256);
function swapUnderlying(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256);
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external returns (uint256);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external returns (uint256[] memory);
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external returns (uint256);
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./IAllowlist.sol";
interface ISwap {
// pool data view functions
function getA() external view returns (uint256);
function getAllowlist() external view returns (IAllowlist);
function getToken(uint8 index) external view returns (IERC20);
function getTokenIndex(address tokenAddress) external view returns (uint8);
function getTokenBalance(uint8 index) external view returns (uint256);
function getVirtualPrice() external view returns (uint256);
function isGuarded() external view returns (bool);
// min return calculation functions
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256);
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256);
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount);
// state modifying functions
function initialize(
IERC20[] memory pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 a,
uint256 fee,
uint256 adminFee,
address lpTokenTargetAddress
) external;
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256);
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external returns (uint256);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external returns (uint256[] memory);
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external returns (uint256);
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "../LPToken.sol";
import "../interfaces/ISwap.sol";
import "../interfaces/IMetaSwap.sol";
/**
* @title MetaSwapDeposit
* @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be
* deployed before this contract can be initialized successfully.
*
* For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT].
* Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either
* the LP token or the underlying tokens and sUSD.
*
* MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users
* to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act
* as a Swap containing [sUSD, DAI, USDC, USDT] tokens.
*/
contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ISwap public baseSwap;
IMetaSwap public metaSwap;
IERC20[] public baseTokens;
IERC20[] public metaTokens;
IERC20[] public tokens;
IERC20 public metaLPToken;
uint256 constant MAX_UINT256 = 2**256 - 1;
struct RemoveLiquidityImbalanceInfo {
ISwap baseSwap;
IMetaSwap metaSwap;
IERC20 metaLPToken;
uint8 baseLPTokenIndex;
bool withdrawFromBase;
uint256 leftoverMetaLPTokenAmount;
}
/**
* @notice Sets the address for the base Swap contract, MetaSwap contract, and the
* MetaSwap LP token contract.
* @param _baseSwap the address of the base Swap contract
* @param _metaSwap the address of the MetaSwap contract
* @param _metaLPToken the address of the MetaSwap LP token contract
*/
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
// Check and approve base level tokens to be deposited to the base Swap contract
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
// Check and approve meta level tokens to be deposited to the MetaSwap contract
IERC20 baseLPToken;
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
// Flatten baseTokens and append it to tokens array
tokens[tokens.length - 1] = baseTokens[0];
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
// Approve base Swap LP token to be burned by the base Swap contract for withdrawing
baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256);
// Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing
_metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256);
// Initialize storage variables
baseSwap = _baseSwap;
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
// Mutative functions
/**
* @notice Swap two underlying tokens using the meta pool and the base pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external nonReentrant returns (uint256) {
tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx);
uint256 tokenToAmount =
metaSwap.swapUnderlying(
tokenIndexFrom,
tokenIndexTo,
dx,
minDy,
deadline
);
tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount);
return tokenToAmount;
}
/**
* @notice Add liquidity to the pool with the given amounts of tokens
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
// Read to memory to save on gas
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
// Transfer base tokens from the caller and deposit to the base Swap pool
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
// if there are any base Swap level tokens, flag it for deposits
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
// Deposit any base Swap level tokens and receive baseLPToken
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
// Transfer remaining meta level tokens from the caller
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
}
}
// Update the baseLPToken amount that will be deposited
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
// Deposit the meta level tokens and the baseLPToken
metaLPTokenAmount = metaSwap.addLiquidity(
metaAmounts,
minToMint,
deadline
);
}
// Transfer the meta lp token to the caller
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount);
return metaLPTokenAmount;
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
// Transfer meta lp token from the caller to this
metaLPToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 baseLPTokenAmount;
{
// Remove liquidity from the MetaSwap pool
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
// Send the meta level tokens to the caller
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
// Remove liquidity from the base Swap pool
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
// Send the base level tokens to the caller
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
uint8 baseTokensLength = uint8(baseTokens.length);
// Transfer metaLPToken from the caller
metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
IERC20 token;
if (tokenIndex < baseLPTokenIndex) {
// When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly
metaSwap.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount,
deadline
);
token = metaTokens[tokenIndex];
} else if (tokenIndex < baseLPTokenIndex + baseTokensLength) {
// When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw
// the desired token from the base Swap contract.
uint256 removedBaseLPTokenAmount =
metaSwap.removeLiquidityOneToken(
tokenAmount,
baseLPTokenIndex,
0,
deadline
);
baseSwap.removeLiquidityOneToken(
removedBaseLPTokenAmount,
tokenIndex - baseLPTokenIndex,
minAmount,
deadline
);
token = baseTokens[tokenIndex - baseLPTokenIndex];
} else {
revert("out of range");
}
uint256 amountWithdrawn = token.balanceOf(address(this));
token.safeTransfer(msg.sender, amountWithdrawn);
return amountWithdrawn;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
// Calculate how much base LP token we need to get the desired amount of underlying tokens
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
// Transfer MetaSwap LP token from the caller to this contract
v.metaLPToken.safeTransferFrom(
msg.sender,
address(this),
maxBurnAmount
);
// Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool
uint256 burnedMetaLPTokenAmount =
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
// If underlying tokens are desired, withdraw them from the base Swap pool
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
// Base Swap may require LESS base LP token than the amount we have
// In that case, deposit it to the MetaSwap pool.
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
// Transfer all withdrawn tokens to the caller
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
} else {
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
// If there were any extra meta lp token, transfer them back to the caller as well
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
// VIEW FUNCTIONS
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running. When withdrawing from the base pool in imbalanced
* fashion, the recommended slippage setting is 0.2% or higher.
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount =
baseSwap.calculateTokenAmount(baseAmounts, deposit);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts =
metaSwap.calculateRemoveLiquidity(amount);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts =
baseSwap.calculateRemoveLiquidity(metaAmounts[baseLPTokenIndex]);
uint256[] memory totalAmounts =
new uint256[](baseLPTokenIndex + baseAmounts.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
if (tokenIndex < baseLPTokenIndex) {
return
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
tokenIndex
);
} else {
uint256 baseLPTokenAmount =
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
baseLPTokenIndex
);
return
baseSwap.calculateRemoveLiquidityOneToken(
baseLPTokenAmount,
tokenIndex - baseLPTokenIndex
);
}
}
/**
* @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range.
* This is a flattened representation of the pooled tokens.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) external view returns (IERC20) {
require(index < tokens.length, "index out of range");
return tokens[index];
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return
metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx);
}
}
| * @title MetaSwapDeposit @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be deployed before this contract can be initialized successfully. For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act as a Swap containing [sUSD, DAI, USDC, USDT] tokens./ | contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ISwap public baseSwap;
IMetaSwap public metaSwap;
IERC20[] public baseTokens;
IERC20[] public metaTokens;
IERC20[] public tokens;
IERC20 public metaLPToken;
uint256 constant MAX_UINT256 = 2**256 - 1;
struct RemoveLiquidityImbalanceInfo {
ISwap baseSwap;
IMetaSwap metaSwap;
IERC20 metaLPToken;
uint8 baseLPTokenIndex;
bool withdrawFromBase;
uint256 leftoverMetaLPTokenAmount;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
} catch {
IERC20 baseLPToken;
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
} catch {
tokens[tokens.length - 1] = baseTokens[0];
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256);
_metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256);
baseSwap = _baseSwap;
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external nonReentrant returns (uint256) {
tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx);
uint256 tokenToAmount =
metaSwap.swapUnderlying(
tokenIndexFrom,
tokenIndexTo,
dx,
minDy,
deadline
);
tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount);
return tokenToAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
}
metaAmounts,
minToMint,
deadline
);
}
return metaLPTokenAmount;
}
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
metaLPTokenAmount = metaSwap.addLiquidity(
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
metaLPToken.safeTransferFrom(msg.sender, address(this), amount);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens =
memBaseTokens.length + memMetaTokens.length - 1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
uint256 baseLPTokenAmount;
{
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts =
new uint256[](memMetaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
{
uint256[] memory baseMinAmounts =
new uint256[](memBaseTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
uint8 baseTokensLength = uint8(baseTokens.length);
metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
IERC20 token;
if (tokenIndex < baseLPTokenIndex) {
metaSwap.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount,
deadline
);
token = metaTokens[tokenIndex];
uint256 removedBaseLPTokenAmount =
metaSwap.removeLiquidityOneToken(
tokenAmount,
baseLPTokenIndex,
0,
deadline
);
baseSwap.removeLiquidityOneToken(
removedBaseLPTokenAmount,
tokenIndex - baseLPTokenIndex,
minAmount,
deadline
);
token = baseTokens[tokenIndex - baseLPTokenIndex];
revert("out of range");
}
uint256 amountWithdrawn = token.balanceOf(address(this));
token.safeTransfer(msg.sender, amountWithdrawn);
return amountWithdrawn;
}
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
uint8 baseTokensLength = uint8(baseTokens.length);
metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
IERC20 token;
if (tokenIndex < baseLPTokenIndex) {
metaSwap.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount,
deadline
);
token = metaTokens[tokenIndex];
uint256 removedBaseLPTokenAmount =
metaSwap.removeLiquidityOneToken(
tokenAmount,
baseLPTokenIndex,
0,
deadline
);
baseSwap.removeLiquidityOneToken(
removedBaseLPTokenAmount,
tokenIndex - baseLPTokenIndex,
minAmount,
deadline
);
token = baseTokens[tokenIndex - baseLPTokenIndex];
revert("out of range");
}
uint256 amountWithdrawn = token.balanceOf(address(this));
token.safeTransfer(msg.sender, amountWithdrawn);
return amountWithdrawn;
}
} else if (tokenIndex < baseLPTokenIndex + baseTokensLength) {
} else {
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
v.metaLPToken.safeTransferFrom(
uint256 burnedMetaLPTokenAmount =
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
} else {
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v =
RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
msg.sender,
address(this),
maxBurnAmount
);
v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount =
baseLPToken.balanceOf(address(this));
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount =
baseSwap.calculateTokenAmount(baseAmounts, deposit);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount =
baseSwap.calculateTokenAmount(baseAmounts, deposit);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount =
baseSwap.calculateTokenAmount(baseAmounts, deposit);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts =
metaSwap.calculateRemoveLiquidity(amount);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts =
baseSwap.calculateRemoveLiquidity(metaAmounts[baseLPTokenIndex]);
uint256[] memory totalAmounts =
new uint256[](baseLPTokenIndex + baseAmounts.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts =
metaSwap.calculateRemoveLiquidity(amount);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts =
baseSwap.calculateRemoveLiquidity(metaAmounts[baseLPTokenIndex]);
uint256[] memory totalAmounts =
new uint256[](baseLPTokenIndex + baseAmounts.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts =
metaSwap.calculateRemoveLiquidity(amount);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts =
baseSwap.calculateRemoveLiquidity(metaAmounts[baseLPTokenIndex]);
uint256[] memory totalAmounts =
new uint256[](baseLPTokenIndex + baseAmounts.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
if (tokenIndex < baseLPTokenIndex) {
return
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
tokenIndex
);
uint256 baseLPTokenAmount =
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
baseLPTokenIndex
);
return
baseSwap.calculateRemoveLiquidityOneToken(
baseLPTokenAmount,
tokenIndex - baseLPTokenIndex
);
}
}
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
if (tokenIndex < baseLPTokenIndex) {
return
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
tokenIndex
);
uint256 baseLPTokenAmount =
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
baseLPTokenIndex
);
return
baseSwap.calculateRemoveLiquidityOneToken(
baseLPTokenAmount,
tokenIndex - baseLPTokenIndex
);
}
}
} else {
function getToken(uint8 index) external view returns (IERC20) {
require(index < tokens.length, "index out of range");
return tokens[index];
}
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return
metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx);
}
}
| 936,480 | [
1,
2781,
12521,
758,
1724,
225,
1220,
6835,
3569,
88,
773,
326,
511,
52,
1147,
316,
279,
6565,
12521,
2845,
364,
15857,
729,
2006,
18,
6565,
12521,
1297,
506,
19357,
1865,
333,
6835,
848,
506,
6454,
4985,
18,
2457,
3454,
16,
1169,
4150,
1915,
1704,
279,
1026,
12738,
2845,
23570,
434,
306,
9793,
45,
16,
11836,
5528,
16,
11836,
9081,
8009,
9697,
279,
6565,
12521,
2845,
848,
506,
2522,
598,
306,
87,
3378,
40,
16,
3360,
12521,
14461,
1345,
65,
358,
1699,
1284,
5489,
3086,
3344,
326,
511,
52,
1147,
578,
326,
6808,
2430,
471,
272,
3378,
40,
18,
6565,
12521,
758,
1724,
3569,
88,
773,
326,
511,
52,
1147,
471,
849,
6679,
2182,
358,
279,
2202,
526,
16,
15632,
3677,
358,
2305,
326,
4904,
603,
3360,
12521,
14461,
1345,
18,
11637,
326,
5721,
3454,
16,
6565,
12521,
758,
1724,
848,
1328,
487,
279,
12738,
4191,
306,
87,
3378,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
6565,
12521,
758,
1724,
353,
10188,
6934,
16,
868,
8230,
12514,
16709,
10784,
429,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
4437,
91,
438,
1071,
1026,
12521,
31,
203,
565,
467,
2781,
12521,
1071,
2191,
12521,
31,
203,
565,
467,
654,
39,
3462,
8526,
1071,
1026,
5157,
31,
203,
565,
467,
654,
39,
3462,
8526,
1071,
2191,
5157,
31,
203,
565,
467,
654,
39,
3462,
8526,
1071,
2430,
31,
203,
565,
467,
654,
39,
3462,
1071,
2191,
14461,
1345,
31,
203,
203,
565,
2254,
5034,
5381,
4552,
67,
57,
3217,
5034,
273,
576,
636,
5034,
300,
404,
31,
203,
203,
203,
565,
1958,
3581,
48,
18988,
24237,
1170,
12296,
966,
288,
203,
3639,
4437,
91,
438,
1026,
12521,
31,
203,
3639,
467,
2781,
12521,
2191,
12521,
31,
203,
3639,
467,
654,
39,
3462,
2191,
14461,
1345,
31,
203,
3639,
2254,
28,
1026,
14461,
1345,
1016,
31,
203,
3639,
1426,
598,
9446,
1265,
2171,
31,
203,
3639,
2254,
5034,
29709,
2781,
14461,
1345,
6275,
31,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
203,
3639,
4437,
91,
438,
389,
1969,
12521,
16,
203,
3639,
467,
2781,
12521,
389,
3901,
12521,
16,
203,
3639,
467,
654,
39,
3462,
389,
3901,
14461,
1345,
203,
565,
262,
3903,
12562,
288,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
5621,
203,
3639,
288,
203,
5411,
2254,
28,
277,
31,
203,
5411,
364,
261,
31,
277,
411,
3847,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "./libraries/LibERC721Matic.sol";
import "../Shared/libraries/LibDiamond.sol";
contract ShroomTopiaMatic {
using Address for address;
using Strings for uint256;
LibERC721Matic.ERC721Storage internal s;
uint256 public constant MAX_SHROOMS = 8950;
uint256 public constant BATCH_LIMIT = 20;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
event WithdrawnBatch(address indexed user, uint256[] tokenIds);
event TransferWithMetadata(address indexed from, address indexed to, uint256 indexed tokenId, bytes metaData);
event MemoChange(uint256 indexed shroomID, string memo);
event NameChange(uint256 indexed shroomID, string name);
function initSale(
uint256 startingIndex_,
string memory baseURI_,
address childChainManagerProxy_
) external {
LibDiamond.enforceIsContractOwner();
s._saleCurrentIndex = startingIndex_;
s._baseURI = baseURI_;
s.childChainManagerProxy = childChainManagerProxy_;
}
function currentPrice() public view returns (uint256) {
uint256 currentSupply = totalSupply();
if (currentSupply < 250) {
return 90000000000000000000; // 0 - 249 90 Matic
} else if (currentSupply < 750) {
return 180000000000000000000; // 250-749: 180 Matic
} else if (currentSupply < 1500) {
return 360000000000000000000; // 750-1499: 360 Matic
} else if (currentSupply < 3000) {
return 720000000000000000000; // 1500-2999: 720 Matic
} else if (currentSupply < 4000) {
return 1425000000000000000000; // 3000-3999: 1425 Matic
} else if (currentSupply < 4250) {
return 2850000000000000000000; // 4000-4249: 2850 Matic
} else if (currentSupply < 4425) {
return 5700000000000000000000; // 4250-4424: 5700 Matic
} else {
return 8900000000000000000000; // 4425-4474: 8900 Matic
}
}
function spawnShrooms(uint256 shroomCount) external payable {
require(totalSupply() > 750 || shroomCount <= 20, "ERC721: Can only mint 20 Shrooms/tx");
require(s._saleCurrentIndex + shroomCount <= MAX_SHROOMS, "ERC721: Exceeds the maximum available shrooms");
require(msg.value >= currentPrice() * shroomCount, "ERC721: Matic value below sale price");
for (uint256 i = 0; i < shroomCount; i++) {
_safeMint(msg.sender, s._saleCurrentIndex);
s._shroomBirthDate[s._saleCurrentIndex] = block.timestamp;
s._saleCurrentIndex += 1;
}
}
function getShroomBday(uint256 tokenId) external view returns (uint256) {
return s._shroomBirthDate[tokenId];
}
function getShroomName(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721: query for nonexistent token");
return s._shroomName[tokenId];
}
function getShroomMemo(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721: query for nonexistent token");
return s._shroomMemo[tokenId];
}
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function withdrawToOwner() external {
LibDiamond.enforceIsContractOwner();
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function changeMemo(uint256 tokenId, string memory memo_) external {
address owner = ownerOf(tokenId);
require(msg.sender == owner, "ERC721: caller is not the owner");
s._shroomMemo[tokenId] = memo_;
emit MemoChange(tokenId, memo_);
}
function changeName(uint256 tokenId, string memory name_) external {
address owner = ownerOf(tokenId);
require(msg.sender == owner, "ERC721: caller is not the owner");
s._shroomName[tokenId] = name_;
emit NameChange(tokenId, name_);
}
function balanceOf(address _owner) public view virtual returns (uint256) {
require(_owner != address(0), "ERC721: balance query for the zero address");
return s._balances[_owner];
}
function ownerOf(uint256 tokenId) public view virtual returns (address) {
address owner = s._owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual returns (string memory) {
return "ShroomTopia(MATIC)";
}
function symbol() public view virtual returns (string memory) {
return "mSTPIA";
}
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(s._baseURI).length > 0 ? string(abi.encodePacked(s._baseURI, tokenId.toString())) : "";
}
function approve(address to, uint256 tokenId) public virtual {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all");
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return s._tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(operator != msg.sender, "ERC721: approve to caller");
s._operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return s._operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
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");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return s._owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
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");
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
_beforeTokenTransfer(address(0), to, tokenId);
s._balances[to] += 1;
s._owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
s._balances[owner] -= 1;
delete s._owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
s._balances[from] -= 1;
s._balances[to] += 1;
s._owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
s._tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, 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 {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {
if (from == address(0)) {
s._totalSupply += 1;
_addTokenToOwnerEnumeration(to, tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
if (to == address(0)) s._totalSupply -= 1;
else _addTokenToOwnerEnumeration(to, tokenId);
}
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to);
s._ownedTokens[to][length] = tokenId;
s._ownedTokensIndex[tokenId] = length;
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = balanceOf(from) - 1;
uint256 tokenIndex = s._ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex];
s._ownedTokens[from][tokenIndex] = lastTokenId;
s._ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete s._ownedTokensIndex[tokenId];
delete s._ownedTokens[from][lastTokenIndex];
}
function totalSupply() public view virtual returns (uint256) {
return s._totalSupply;
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return s._ownedTokens[owner][index];
}
function deposit(address user, bytes calldata depositData) external {
require(msg.sender == s.childChainManagerProxy, "ChildMintableERC721: INSUFFICIENT_PERMISSIONS");
if (depositData.length == 32) {
uint256 tokenId = abi.decode(depositData, (uint256));
s.withdrawnTokens[tokenId] = false;
_mint(user, tokenId);
} else {
uint256[] memory tokenIds = abi.decode(depositData, (uint256[]));
uint256 length = tokenIds.length;
for (uint256 i; i < length; i++) {
s.withdrawnTokens[tokenIds[i]] = false;
_mint(user, tokenIds[i]);
}
}
}
function withdraw(uint256 tokenId) external {
require(msg.sender == ownerOf(tokenId), "ChildMintableERC721: INVALID_TOKEN_OWNER");
s.withdrawnTokens[tokenId] = true;
_burn(tokenId);
}
function withdrawBatch(uint256[] calldata tokenIds) external {
uint256 length = tokenIds.length;
require(length <= BATCH_LIMIT, "ChildMintableERC721: EXCEEDS_BATCH_LIMIT");
for (uint256 i; i < length; i++) {
uint256 tokenId = tokenIds[i];
require(msg.sender == ownerOf(tokenId), string(abi.encodePacked("ChildMintableERC721: INVALID_TOKEN_OWNER ", tokenId)));
s.withdrawnTokens[tokenId] = true;
_burn(tokenId);
}
emit WithdrawnBatch(msg.sender, tokenIds);
}
}
| 0 - 249 90 Matic
| return 90000000000000000000; | 1,779,710 | [
1,
20,
300,
4248,
29,
377,
8566,
490,
2126,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
327,
2468,
12648,
12648,
3784,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-23
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/IAssetManager.sol
pragma solidity ^0.7.6;
/// @title Asset Manager - The asset manager interface
/// @notice This contract is used to manage fund asset
interface IAssetManager {
/// @notice Total asset
/// @dev This function calculates the net worth or AUM
/// @return Total asset
function assets()external view returns(uint256);
/// @notice Withdraw asset
/// @dev Only fund contract can withdraw asset
/// @param to Withdraw address
/// @param amount Withdraw amount
/// @param scale Withdraw percentage
function withdraw(address to,uint256 amount,uint256 scale)external;
/// @notice Withdraw underlying asset
/// @dev Only fund contract can withdraw underlying asset
/// @param to Withdraw address
/// @param scale Withdraw percentage
function withdrawOfUnderlying(address to,uint256 scale)external;
}
// File: contracts/interfaces/erc20/IERC20Metadata.sol
pragma solidity ^0.7.6;
interface IERC20Metadata {
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function decimals() external view returns(uint8);
}
// File: contracts/libraries/SafeMathExtends.sol
pragma solidity ^0.7.6;
// a library for performing various math operations
library SafeMathExtends {
uint256 internal constant BONE = 10 ** 18;
// Add two numbers together checking for overflows
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
// subtract two numbers and return diffecerence when it underflows
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
// Subtract two numbers checking for underflows
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
// Multiply two 18 decimals numbers
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BONE;
return c2;
}
// Divide two 18 decimals numbers
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL");
// bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL");
// badd require
uint256 c2 = c1 / b;
return c2;
}
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
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;
}
}
}
// File: contracts/storage/SmartPoolStorage.sol
pragma solidity ^0.7.6;
library SmartPoolStorage {
bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location");
struct Storage {
address controller;
uint256 cap;
mapping(FeeType => Fee) fees;
mapping(address => uint256) nets;
address token;
address am;
bool bind;
bool suspend;
bool allowJoin;
bool allowExit;
}
struct Fee {
uint256 ratio;
uint256 denominator;
uint256 lastTimestamp;
uint256 minLine;
}
enum FeeType{
JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE
}
function load() internal pure returns (Storage storage s) {
bytes32 loc = sSlot;
assembly {
s.slot := loc
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
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 { }
}
// File: contracts/storage/GovIdentityStorage.sol
pragma solidity ^0.7.6;
library GovIdentityStorage {
bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location");
struct Identity{
address governance;
address strategist;
address rewards;
}
function load() internal pure returns (Identity storage gov) {
bytes32 loc = govSlot;
assembly {
gov.slot := loc
}
}
}
// File: contracts/base/GovIdentity.sol
pragma solidity ^0.7.6;
contract GovIdentity {
constructor() {
_init();
}
function _init() internal{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.governance = msg.sender;
identity.strategist = msg.sender;
identity.rewards = msg.sender;
}
modifier onlyStrategist() {
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
require(msg.sender == identity.strategist, "GovIdentity.onlyStrategist: !strategist");
_;
}
modifier onlyGovernance() {
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
require(msg.sender == identity.governance, "GovIdentity.onlyGovernance: !governance");
_;
}
modifier onlyStrategistOrGovernance() {
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
require(msg.sender == identity.strategist || msg.sender == identity.governance, "GovIdentity.onlyGovernance: !governance and !strategist");
_;
}
function setRewards(address _rewards) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.rewards = _rewards;
}
function setStrategist(address _strategist) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.strategist = _strategist;
}
function setGovernance(address _governance) public onlyGovernance{
GovIdentityStorage.Identity storage identity= GovIdentityStorage.load();
identity.governance = _governance;
}
function getRewards() public pure returns(address){
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
return identity.rewards ;
}
function getStrategist() public pure returns(address){
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
return identity.strategist;
}
function getGovernance() public pure returns(address){
GovIdentityStorage.Identity memory identity= GovIdentityStorage.load();
return identity.governance;
}
}
// File: contracts/base/BasicFund.sol
pragma solidity ^0.7.6;
pragma abicoder v2;
/// @title Basic Fund - Abstract Fund definition
/// @notice This contract extends ERC20, defines basic fund functions and rewrites ERC20 transferFrom function
abstract contract BasicFund is ERC20, GovIdentity {
using SafeMath for uint256;
uint8 internal _decimals;
event CapChanged(address indexed setter, uint256 oldCap, uint256 newCap);
event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee);
event FeeChanged(address indexed setter, uint256 oldRatio, uint256 oldDenominator, uint256 newRatio, uint256 newDenominator);
constructor(
string memory name_,
string memory symbol_
)ERC20(name_, symbol_) {
super._init();
}
/// @notice ιεΆεΊιεθ‘ι
modifier withinCap() {
_;
uint256 cap = SmartPoolStorage.load().cap;
bool check = cap == 0 || totalSupply() <= cap ? true : false;
require(check, "BasicFund.withinCap: Cap limit reached");
}
/// @notice Prohibition of fund circulation
modifier deny() {
require(!SmartPoolStorage.load().suspend, "BasicFund.isNotSuspend: fund is suspend");
_;
}
/// @notice is allow join
modifier isAllowJoin() {
require(checkAllowJoin(), "BasicFund.checkAllowJoin: fund is not allowJoin");
_;
}
/// @notice is allow exit
modifier isAllowExit() {
require(checkAllowExit(), "BasicFund.checkAllowExit: fund is not allowExit");
_;
}
/// @notice Check allow join
/// @return bool
function checkAllowJoin()public view returns(bool){
return SmartPoolStorage.load().allowJoin;
}
/// @notice Check allow exit
/// @return bool
function checkAllowExit()public view returns(bool){
return SmartPoolStorage.load().allowExit;
}
/// @notice Fund decimals
/// @dev This function rewrites ERC20 decimals function
/// @return decimals
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/// @notice Update weighted average net worth
/// @dev This function is used by the new transferFrom/transfer function
/// @param account Account address
/// @param addAmount Newly added fund amount
/// @param newNet New weighted average net worth
function _updateAvgNet(address account, uint256 addAmount, uint256 newNet) internal {
uint256 balance = balanceOf(account);
uint256 oldNet = SmartPoolStorage.load().nets[account];
uint256 total = balance.add(addAmount);
if (total != 0) {
uint256 nextNet = oldNet.mul(balance).add(newNet.mul(addAmount)).div(total);
SmartPoolStorage.load().nets[account] = nextNet;
}
}
/// @notice Overwrite transfer function
/// @dev The purpose is to update weighted average net worth
/// @param sender Sender address
/// @param recipient Recipient address
/// @param amount Transfer amount
function _transfer(address sender, address recipient, uint256 amount) internal virtual override deny {
uint256 newNet = SmartPoolStorage.load().nets[sender];
_updateAvgNet(recipient, amount, newNet);
super._transfer(sender, recipient, amount);
if (balanceOf(sender) == 0) {
SmartPoolStorage.load().nets[sender] = 0;
}
}
/// @notice Overwrite mint function
/// @dev the purpose is to set the initial net worth of the fund. It also limit the max fund cap
/// @param recipient Recipient address
/// @param amount Mint amount
function _mint(address recipient, uint256 amount) internal virtual override withinCap deny {
uint256 newNet = globalNetValue();
if (newNet == 0) newNet = 1e18;
_updateAvgNet(recipient, amount, newNet);
super._mint(recipient, amount);
}
/// @notice Overwrite burn function
/// @dev The purpose is to set the net worth of fund to 0 when the balance of the account is 0
/// @param account Account address
/// @param amount Burn amount
function _burn(address account, uint256 amount) internal virtual override deny {
super._burn(account, amount);
if (balanceOf(account) == 0) {
SmartPoolStorage.load().nets[account] = 0;
}
}
/// @notice Overwrite fund transferFrom function
/// @dev The overwrite is to simplify the transaction behavior, and the authorization operation behavior can be avoided when the fund transaction payer is the function initiator
/// @param sender Sender address
/// @param recipient Recipient address
/// @param amount Transfer amount
/// @return Transfer result
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
require(
_msgSender() == sender || amount <= allowance(sender, _msgSender()),
"ERR_KTOKEN_BAD_CALLER"
);
_transfer(sender, recipient, amount);
if (_msgSender() != sender) {
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "BasicFund: transfer amount exceeds allowance"));
}
return true;
}
/// @notice Fund cap
/// @dev The max number of fund to be issued
/// @return Max fund cap
function getCap() public view returns (uint256){
return SmartPoolStorage.load().cap;
}
/// @notice Set max fund cap
/// @dev To set max fund cap
/// @param cap Max fund cap
function setCap(uint256 cap) external onlyStrategistOrGovernance {
uint256 oldCap = SmartPoolStorage.load().cap;
SmartPoolStorage.load().cap = cap;
emit CapChanged(msg.sender, oldCap, cap);
}
/// @notice The net worth of the fund from the time the last fee collected
/// @dev This is used to calculate the performance fee
/// @param account Account address
/// @return The net worth of the fund
function accountNetValue(address account) public view returns (uint256){
return SmartPoolStorage.load().nets[account];
}
/// @notice The current fund net worth
/// @dev This is used to update and calculate account net worth
/// @return The net worth of the fund
function globalNetValue() public view returns (uint256){
return convertToCash(1e18);
}
/// @notice Get fee by type
/// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE)
/// @param ft Fee type
function getFee(SmartPoolStorage.FeeType ft) public view returns (SmartPoolStorage.Fee memory){
return SmartPoolStorage.load().fees[ft];
}
/// @notice Set fee by type
/// @dev Only Governance address can set fees (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE)
/// @param ft Fee type
/// @param ratio Fee ratio
/// @param denominator The max ratio limit
/// @param minLine The minimum line to charge a fee
function setFee(SmartPoolStorage.FeeType ft, uint256 ratio, uint256 denominator, uint256 minLine) external onlyGovernance {
require(ratio <= denominator, "BasicFund.setFee: ratio<=denominator");
SmartPoolStorage.Fee storage fee = SmartPoolStorage.load().fees[ft];
require(fee.denominator == 0, "BasicFund.setFee: already initialized ");
emit FeeChanged(msg.sender, fee.ratio, fee.denominator, ratio, denominator);
fee.ratio = ratio;
fee.denominator = denominator;
fee.minLine = minLine;
fee.lastTimestamp = block.timestamp;
}
/// @notice Collect outstanding management fee
/// @dev The outstanding management fee is calculated from the time the last fee is collected.
function takeOutstandingManagementFee() public returns (uint256){
SmartPoolStorage.Fee storage fee = SmartPoolStorage.load().fees[SmartPoolStorage.FeeType.MANAGEMENT_FEE];
uint256 outstandingFee = calcManagementFee();
if (outstandingFee == 0 || outstandingFee < fee.minLine) return 0;
_mint(getRewards(), outstandingFee);
fee.lastTimestamp = block.timestamp;
emit TakeFee(SmartPoolStorage.FeeType.MANAGEMENT_FEE, address(0), outstandingFee);
return outstandingFee;
}
/// @notice Collect performance fee
/// @dev Performance fee is calculated by each address. The new net worth of the address is updated each time the performance is collected.
/// @param target Account address to collect performance fee
function takeOutstandingPerformanceFee(address target) public returns (uint256){
if (target == getRewards()) return 0;
uint256 netValue = globalNetValue();
SmartPoolStorage.Fee storage fee = SmartPoolStorage.load().fees[SmartPoolStorage.FeeType.PERFORMANCE_FEE];
uint256 outstandingFee = calcPerformanceFee(target, netValue);
if (outstandingFee == 0 || outstandingFee < fee.minLine) return 0;
_transfer(target, getRewards(), outstandingFee);
fee.lastTimestamp = block.timestamp;
SmartPoolStorage.load().nets[target] = netValue;
emit TakeFee(SmartPoolStorage.FeeType.PERFORMANCE_FEE, target, outstandingFee);
return outstandingFee;
}
/// @notice Collect Join fee
/// @dev The join fee is collected each time a user buys the fund
/// @param target Account address to collect join fee
/// @param fundAmount Fund amount
function _takeJoinFee(address target, uint256 fundAmount) internal returns (uint256){
if (target == getRewards()) return 0;
SmartPoolStorage.Fee memory fee = getFee(SmartPoolStorage.FeeType.JOIN_FEE);
uint256 payFee = calcRatioFee(SmartPoolStorage.FeeType.JOIN_FEE, fundAmount);
if (payFee == 0 || payFee < fee.minLine) return 0;
_mint(getRewards(), payFee);
emit TakeFee(SmartPoolStorage.FeeType.JOIN_FEE, target, payFee);
return payFee;
}
/// @notice Collect Redeem fee
/// @dev The redeem fee is collected when a user redeems the fund
/// @param target Account address to collect redeem fee
/// @param fundAmount Fund amount
function _takeExitFee(address target, uint256 fundAmount) internal returns (uint256){
if (target == getRewards()) return 0;
SmartPoolStorage.Fee memory fee = getFee(SmartPoolStorage.FeeType.EXIT_FEE);
uint256 payFee = calcRatioFee(SmartPoolStorage.FeeType.EXIT_FEE, fundAmount);
if (payFee == 0 || payFee < fee.minLine) return 0;
_transfer(target, getRewards(), payFee);
emit TakeFee(SmartPoolStorage.FeeType.EXIT_FEE, target, payFee);
return payFee;
}
/// @notice Calculate management fee
/// @dev Outstanding management fee is calculated from the time the last fee is collected.
function calcManagementFee() public view returns (uint256){
SmartPoolStorage.Fee memory fee = getFee(SmartPoolStorage.FeeType.MANAGEMENT_FEE);
uint256 denominator = fee.denominator == 0 ? 1000 : fee.denominator;
if (fee.lastTimestamp == 0) return 0;
uint256 diff = block.timestamp.sub(fee.lastTimestamp);
return totalSupply().mul(diff).mul(fee.ratio).div(denominator * 365.25 days);
}
/// @notice Calculate performance fee
/// @dev Performance fee is calculated by each address. The new net worth line of the address is updated each time the performance is collected.
/// @param target Account address to collect performance fee
/// @param newNet New net worth
function calcPerformanceFee(address target, uint256 newNet) public view returns (uint256){
if (newNet == 0) return 0;
uint256 balance = balanceOf(target);
uint256 oldNet = accountNetValue(target);
uint256 diff = newNet > oldNet ? newNet.sub(oldNet) : 0;
SmartPoolStorage.Fee memory fee = getFee(SmartPoolStorage.FeeType.PERFORMANCE_FEE);
uint256 denominator = fee.denominator == 0 ? 1000 : fee.denominator;
uint256 cash = diff.mul(balance).mul(fee.ratio).div(denominator);
return cash.div(newNet);
}
/// @notice Calculate the fee by ratio
/// @dev This is used to calculate join and redeem fee
/// @param ft Fee type
/// @param fundAmount Fund amount
function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 fundAmount) public view returns (uint256){
if (fundAmount == 0) return 0;
SmartPoolStorage.Fee memory fee = getFee(ft);
uint256 denominator = fee.denominator == 0 ? 1000 : fee.denominator;
uint256 amountRatio = fundAmount.div(denominator);
return amountRatio.mul(fee.ratio);
}
//@notice fund maintenance
//@dev stop and open fund circulation
/// @param _value status value
function maintain(bool _value) external onlyStrategistOrGovernance {
SmartPoolStorage.load().suspend = _value;
}
//@notice fund allowJoin
//@dev stop and open fund circulation
/// @param _value status value
function allowJoin(bool _value) external onlyStrategistOrGovernance {
SmartPoolStorage.load().allowJoin = _value;
}
//@notice fund allowExit
//@dev stop and open fund circulation
/// @param _value status value
function allowExit(bool _value) external onlyStrategistOrGovernance {
SmartPoolStorage.load().allowExit = _value;
}
/// @notice Convert fund amount to cash amount
/// @dev This converts the user fund amount to cash amount when a user redeems the fund
/// @param fundAmount Redeem fund amount
/// @return Cash amount
function convertToCash(uint256 fundAmount) public virtual view returns (uint256);
/// @notice Convert cash amount to fund amount
/// @dev This converts cash amount to fund amount when a user buys the fund
/// @param cashAmount Join cash amount
/// @return Fund amount
function convertToFund(uint256 cashAmount) public virtual view returns (uint256);
}
// File: contracts/Fund.sol
pragma solidity ^0.7.6;
/// @title Fund Contract - The implmentation of fund contract
/// @notice This contract extends Basic Fund and defines the join and redeem activities
contract Fund is BasicFund {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMathExtends for uint256;
using Address for address;
event PoolJoined(address indexed investor, uint256 amount);
event PoolExited(address indexed investor, uint256 amount);
/// @notice deny contract
modifier notAllowContract() {
require(!address(msg.sender).isContract(), "Fund.notContract: sender is contract ");
_;
}
constructor(
string memory name,
string memory symbol
) BasicFund(name, symbol){
}
/// @notice Bind join and redeem address with asset management contract
/// @dev Make the accuracy of the fund consistent with the accuracy of the bound token; it can only be bound once and cannot be modified
/// @param token Join and redeem fund token address
/// @param am Asset managemeent address
function bind(address token, address am) external onlyGovernance {
require(!SmartPoolStorage.load().bind, "Fund.bind: already bind");
_decimals = IERC20Metadata(token).decimals();
SmartPoolStorage.load().token = token;
SmartPoolStorage.load().am = am;
SmartPoolStorage.load().bind = true;
SmartPoolStorage.load().suspend = false;
SmartPoolStorage.load().allowJoin = true;
SmartPoolStorage.load().allowExit = true;
}
/// @notice Subscript fund
/// @dev When subscribing to the fund, fee will be collected, and contract access is not allowed
/// @param amount Subscription amount
function joinPool(uint256 amount) external isAllowJoin notAllowContract {
address investor = msg.sender;
require(amount <= ioToken().balanceOf(investor) && amount > 0, "Fund.joinPool: Insufficient balance");
uint256 fundAmount = convertToFund(amount);
//take management fee
takeOutstandingManagementFee();
//take join fee
uint256 fee = _takeJoinFee(investor, fundAmount);
uint256 realFundAmount = fundAmount.sub(fee);
_mint(investor, realFundAmount);
ioToken().safeTransferFrom(investor, AM(), amount);
emit PoolJoined(investor, realFundAmount);
}
/// @notice Redeem fund
/// @dev When the fund is redeemed, fees will be collected, and contract access is not allowed
/// @param amount Redeem amount
function exitPool(uint256 amount) external isAllowExit notAllowContract {
address investor = msg.sender;
require(balanceOf(investor) >= amount && amount > 0, "Fund.exitPool: Insufficient balance");
//take exit fee
uint256 exitFee = _takeExitFee(investor, amount);
uint256 exitAmount = amount.sub(exitFee);
//take performance fee
uint256 perFee = takeOutstandingPerformanceFee(investor);
exitAmount = exitAmount.sub(perFee);
uint256 scale = exitAmount.bdiv(totalSupply());
uint256 cashAmount = convertToCash(exitAmount);
//take management fee
takeOutstandingManagementFee();
// withdraw cash
IAssetManager(AM()).withdraw(investor, cashAmount, scale);
_burn(investor, exitAmount);
emit PoolExited(investor, amount);
}
/// @notice Redeem the underlying assets of the fund
/// @dev When the fund is redeemed, fees will be collected, and contract access is not allowed
/// @param amount Redeem amount
function exitPoolOfUnderlying(uint256 amount) external isAllowExit notAllowContract {
address investor = msg.sender;
require(balanceOf(investor) >= amount && amount > 0, "Fund.exitPoolOfUnderlying: Insufficient balance");
//take exit fee
uint256 exitFee = _takeExitFee(investor, amount);
uint256 exitAmount = amount.sub(exitFee);
//take performance fee
uint256 perFee = takeOutstandingPerformanceFee(investor);
exitAmount = exitAmount.sub(perFee);
uint256 scale = exitAmount.bdiv(totalSupply());
//take management fee
takeOutstandingManagementFee();
//harvest underlying
IAssetManager(AM()).withdrawOfUnderlying(investor, scale);
_burn(investor, exitAmount);
emit PoolExited(investor, amount);
}
/// @notice Fund token address for joining and redeeming
/// @dev This is address is created when the fund is first created.
/// @return Fund token address
function ioToken() public view returns (IERC20){
return IERC20(SmartPoolStorage.load().token);
}
/// @notice Fund mangement contract address
/// @dev The fund management contract address is bind to the fund when the fund is created
/// @return Fund management contract address
function AM() public view returns (address){
return SmartPoolStorage.load().am;
}
/// @notice Convert fund amount to cash amount
/// @dev This converts the user fund amount to cash amount when a user redeems the fund
/// @param fundAmount Redeem fund amount
/// @return Cash amount
function convertToCash(uint256 fundAmount) public virtual override view returns (uint256){
uint256 cash = 0;
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
cash = 0;
} else {
cash = _assets.mul(fundAmount).div(totalSupply);
}
return cash;
}
/// @notice Convert cash amount to fund amount
/// @dev This converts cash amount to fund amount when a user buys the fund
/// @param cashAmount Join cash amount
/// @return Fund amount
function convertToFund(uint256 cashAmount) public virtual override view returns (uint256){
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
return cashAmount;
} else {
return cashAmount.mul(totalSupply).div(_assets);
}
}
/// @notice Fund total asset
/// @dev This calculates fund net worth or AUM
/// @return Fund total asset
function assets() public view returns (uint256){
return IAssetManager(AM()).assets();
}
} | @notice Convert fund amount to cash amount @dev This converts the user fund amount to cash amount when a user redeems the fund @param fundAmount Redeem fund amount @return Cash amount @notice Convert cash amount to fund amount @dev This converts cash amount to fund amount when a user buys the fund @param cashAmount Join cash amount @return Fund amount File: contracts/Fund.sol @title Fund Contract - The implmentation of fund contract @notice This contract extends Basic Fund and defines the join and redeem activities | contract Fund is BasicFund {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMathExtends for uint256;
using Address for address;
event PoolJoined(address indexed investor, uint256 amount);
event PoolExited(address indexed investor, uint256 amount);
function convertToCash(uint256 fundAmount) public virtual view returns (uint256);
function convertToFund(uint256 cashAmount) public virtual view returns (uint256);
}
pragma solidity ^0.7.6;
modifier notAllowContract() {
require(!address(msg.sender).isContract(), "Fund.notContract: sender is contract ");
_;
}
constructor(
string memory name,
string memory symbol
) BasicFund(name, symbol){
}
function bind(address token, address am) external onlyGovernance {
require(!SmartPoolStorage.load().bind, "Fund.bind: already bind");
_decimals = IERC20Metadata(token).decimals();
SmartPoolStorage.load().token = token;
SmartPoolStorage.load().am = am;
SmartPoolStorage.load().bind = true;
SmartPoolStorage.load().suspend = false;
SmartPoolStorage.load().allowJoin = true;
SmartPoolStorage.load().allowExit = true;
}
function joinPool(uint256 amount) external isAllowJoin notAllowContract {
address investor = msg.sender;
require(amount <= ioToken().balanceOf(investor) && amount > 0, "Fund.joinPool: Insufficient balance");
uint256 fundAmount = convertToFund(amount);
takeOutstandingManagementFee();
uint256 fee = _takeJoinFee(investor, fundAmount);
uint256 realFundAmount = fundAmount.sub(fee);
_mint(investor, realFundAmount);
ioToken().safeTransferFrom(investor, AM(), amount);
emit PoolJoined(investor, realFundAmount);
}
function exitPool(uint256 amount) external isAllowExit notAllowContract {
address investor = msg.sender;
require(balanceOf(investor) >= amount && amount > 0, "Fund.exitPool: Insufficient balance");
uint256 exitFee = _takeExitFee(investor, amount);
uint256 exitAmount = amount.sub(exitFee);
uint256 perFee = takeOutstandingPerformanceFee(investor);
exitAmount = exitAmount.sub(perFee);
uint256 scale = exitAmount.bdiv(totalSupply());
uint256 cashAmount = convertToCash(exitAmount);
takeOutstandingManagementFee();
IAssetManager(AM()).withdraw(investor, cashAmount, scale);
_burn(investor, exitAmount);
emit PoolExited(investor, amount);
}
function exitPoolOfUnderlying(uint256 amount) external isAllowExit notAllowContract {
address investor = msg.sender;
require(balanceOf(investor) >= amount && amount > 0, "Fund.exitPoolOfUnderlying: Insufficient balance");
uint256 exitFee = _takeExitFee(investor, amount);
uint256 exitAmount = amount.sub(exitFee);
uint256 perFee = takeOutstandingPerformanceFee(investor);
exitAmount = exitAmount.sub(perFee);
uint256 scale = exitAmount.bdiv(totalSupply());
takeOutstandingManagementFee();
IAssetManager(AM()).withdrawOfUnderlying(investor, scale);
_burn(investor, exitAmount);
emit PoolExited(investor, amount);
}
function ioToken() public view returns (IERC20){
return IERC20(SmartPoolStorage.load().token);
}
function AM() public view returns (address){
return SmartPoolStorage.load().am;
}
function convertToCash(uint256 fundAmount) public virtual override view returns (uint256){
uint256 cash = 0;
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
cash = 0;
cash = _assets.mul(fundAmount).div(totalSupply);
}
return cash;
}
function convertToCash(uint256 fundAmount) public virtual override view returns (uint256){
uint256 cash = 0;
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
cash = 0;
cash = _assets.mul(fundAmount).div(totalSupply);
}
return cash;
}
} else {
function convertToFund(uint256 cashAmount) public virtual override view returns (uint256){
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
return cashAmount;
return cashAmount.mul(totalSupply).div(_assets);
}
}
function convertToFund(uint256 cashAmount) public virtual override view returns (uint256){
uint256 totalSupply = totalSupply();
uint256 _assets = assets();
if (totalSupply == 0 || _assets == 0) {
return cashAmount;
return cashAmount.mul(totalSupply).div(_assets);
}
}
} else {
function assets() public view returns (uint256){
return IAssetManager(AM()).assets();
}
} | 6,627,275 | [
1,
2723,
284,
1074,
3844,
358,
276,
961,
3844,
225,
1220,
7759,
326,
729,
284,
1074,
3844,
358,
276,
961,
3844,
1347,
279,
729,
283,
323,
7424,
326,
284,
1074,
225,
284,
1074,
6275,
868,
24903,
284,
1074,
3844,
327,
385,
961,
3844,
225,
4037,
276,
961,
3844,
358,
284,
1074,
3844,
225,
1220,
7759,
276,
961,
3844,
358,
284,
1074,
3844,
1347,
279,
729,
25666,
1900,
326,
284,
1074,
225,
276,
961,
6275,
4214,
276,
961,
3844,
327,
478,
1074,
3844,
1387,
30,
20092,
19,
42,
1074,
18,
18281,
225,
478,
1074,
13456,
300,
1021,
9380,
475,
367,
434,
284,
1074,
6835,
225,
1220,
6835,
3231,
7651,
478,
1074,
471,
11164,
326,
1233,
471,
283,
24903,
17259,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
478,
1074,
353,
7651,
42,
1074,
288,
203,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
10477,
19581,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
871,
8828,
4572,
329,
12,
2867,
8808,
2198,
395,
280,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
8828,
6767,
329,
12,
2867,
8808,
2198,
395,
280,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
8137,
39,
961,
12,
11890,
5034,
284,
1074,
6275,
13,
1071,
5024,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
8137,
42,
1074,
12,
11890,
5034,
276,
961,
6275,
13,
1071,
5024,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
26,
31,
203,
203,
565,
9606,
486,
7009,
8924,
1435,
288,
203,
3639,
2583,
12,
5,
2867,
12,
3576,
18,
15330,
2934,
291,
8924,
9334,
315,
42,
1074,
18,
902,
8924,
30,
5793,
353,
6835,
315,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
203,
565,
262,
7651,
42,
1074,
12,
529,
16,
3273,
15329,
203,
203,
565,
289,
203,
203,
565,
445,
1993,
12,
2867,
1147,
16,
1758,
2125,
13,
3903,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
2583,
12,
5,
23824,
2864,
3245,
18,
945,
7675,
4376,
16,
315,
42,
1074,
18,
4376,
2
] |
./full_match/80001/0x593c1490121bEF64347dc951633bAA1Dc3526E38/sources/contracts/1_Storage.sol | * @dev Gets initial fee percentage that applies to first buyings @return percentage of initial fee with 2 decimals/* @dev Gets buying fee percentage that applies to all buyings except first one @return percentage of buying fee with 2 decimals/* @dev Interface of the ERC20 standard as defined in the EIP./ | interface IToken is IERC20 {
function decimals() external view returns (uint8);
}
| 9,471,049 | [
1,
3002,
2172,
14036,
11622,
716,
10294,
358,
1122,
30143,
899,
327,
11622,
434,
2172,
14036,
598,
576,
15105,
19,
225,
11881,
30143,
310,
14036,
11622,
716,
10294,
358,
777,
30143,
899,
1335,
1122,
1245,
327,
11622,
434,
30143,
310,
14036,
598,
576,
15105,
19,
225,
6682,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
1345,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
15105,
1435,
3903,
1476,
1135,
261,
11890,
28,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/**
* @title SafeMathΖ
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
Note: Simple contract to use as base for const vals
*/
contract CommonConstants {
bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the batch transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _ids An array containing ids of each token being transferred (order and length must match _values array)
@param _values An array containing amounts of each token being transferred (order and length must match _ids array)
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}
/**
@title ERC-1155 Multi Token Standard
@dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 /* is ERC165 */ {
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _tokenId);
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
struct Royalties {
address issuer;
uint256 royalties;
}
contract ERC1155 is IERC1155, ERC165, CommonConstants
{
using SafeMath for uint256;
using Address for address;
mapping (uint256 => mapping(address => uint256)) internal balances;
mapping (address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
//bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external override {
require(_to != address(0x0), "_to must be non-zero.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external override{
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(_ids.length == _values.length, "_ids and _values array length must match.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external override view returns (uint256) {
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external override view returns (uint256[] memory) {
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external override {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
}
function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
}
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a;
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
bytes4 private constant _INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public royalties;
mapping (uint256 => string) public uri;
uint public nonce;
string public name = "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88";
string public symbol = "\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88";
string private collectionUri = "ipfs://QmQ5j4yPAPoCJLWVQvLJRHASXuTGzSRajByByMuL1odZoZ";
function mint(uint256 _initialSupply, uint256 _royalties, string memory _tokenUri) public returns(uint256 _id) {
require(_royalties >= 0 && _royalties <= 2500 && _initialSupply > 0 && _initialSupply <= 20000 && bytes(_tokenUri).length > 0);
// add βββ fee?
_id = ++nonce;
creators[_id] = msg.sender;
balances[_id][msg.sender] = _initialSupply;
royalties[_id] = _royalties;
emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _initialSupply);
uri[_id] = _tokenUri;
emit URI(_tokenUri, _id);
return _id;
}
function supportsInterface(bytes4 interfaceId) public override view returns (bool) {
return interfaceId == _INTERFACE_ID_ERC1155 || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_SIGNATURE_ERC165;
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) {
return (creators[_tokenId], _salePrice*royalties[_tokenId]/10000);
}
// https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) { return collectionUri; }
}
| / The balance of any account can be calculated from the Transfer events history. However, since we need to keep the balances to validate transfer request, there is no extra cost to also privide a querry function. | function balanceOf(address _owner, uint256 _id) external override view returns (uint256) {
return balances[_id][_owner];
}
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
| 12,579,671 | [
1,
19,
1021,
11013,
434,
1281,
2236,
848,
506,
8894,
628,
326,
12279,
2641,
4927,
18,
10724,
16,
3241,
732,
1608,
358,
3455,
326,
324,
26488,
358,
1954,
7412,
590,
16,
1915,
353,
1158,
2870,
6991,
358,
2546,
6015,
831,
279,
719,
21938,
445,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11013,
951,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
350,
13,
3903,
3849,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
324,
26488,
63,
67,
350,
6362,
67,
8443,
15533,
203,
565,
289,
203,
203,
203,
3639,
632,
891,
389,
995,
414,
1021,
6138,
434,
326,
1147,
366,
4665,
203,
3639,
632,
891,
389,
2232,
565,
1599,
434,
326,
13899,
203,
3639,
632,
2463,
3639,
1021,
389,
8443,
1807,
11013,
434,
326,
3155,
1953,
3764,
261,
77,
18,
73,
18,
11013,
364,
1517,
261,
8443,
16,
612,
13,
3082,
13,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x13efc83c17e245FE54ee470c5A0Fe59FF5DbCA35/sources/NinetoFive.sol | 0.5% of total supply
| uint256 amount = (_totalSupply * 50) / 10_000; | 2,695,346 | [
1,
20,
18,
25,
9,
434,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
3844,
273,
261,
67,
4963,
3088,
1283,
380,
6437,
13,
342,
1728,
67,
3784,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
// File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol
/**
* @title Block Relay Interface
* @notice Interface of a Block Relay to a Witnet network
* It defines how to interact with the Block Relay in order to support:
* - Retrieve last beacon information
* - Verify proof of inclusions (PoIs) of data request and tally transactions
* @author Witnet Foundation
*/
interface BlockRelayInterface {
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory);
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view returns(uint256);
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view returns(uint256);
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies the validity of a tally PoI against the Tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid tally PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies if the block relay can be upgraded
/// @return true if contract is upgradable
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol
/**
* @title Block relay contract
* @notice Contract to store/read block headers from the Witnet network
* @author Witnet Foundation
*/
contract CentralizedBlockRelay is BlockRelayInterface {
struct MerkleRoots {
// hash of the merkle root of the DRs in Witnet
uint256 drHashMerkleRoot;
// hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
}
struct Beacon {
// hash of the last block
uint256 blockHash;
// epoch of the last block
uint256 epoch;
}
// Address of the block pusher
address public witnet;
// Last block reported
Beacon public lastBlock;
mapping (uint256 => MerkleRoots) public blocks;
// Event emitted when a new block is posted to the contract
event NewBlock(address indexed _from, uint256 _id);
// Only the owner should be able to push blocks
modifier isOwner() {
require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts.
_; // Otherwise, it continues.
}
// Ensures block exists
modifier blockExists(uint256 _id){
require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block");
_;
}
// Ensures block does not exist
modifier blockDoesNotExist(uint256 _id){
require(blocks[_id].drHashMerkleRoot==0, "The block already existed");
_;
}
constructor() public{
// Only the contract deployer is able to push blocks
witnet = msg.sender;
}
/// @dev Read the beacon of the last block inserted
/// @return bytes to be signed by bridge nodes
function getLastBeacon()
external
view
override
returns(bytes memory)
{
return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch);
}
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view override returns(uint256) {
return lastBlock.epoch;
}
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view override returns(uint256) {
return lastBlock.blockHash;
}
/// @dev Verifies the validity of a PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot;
return(verifyPoi(
_poi,
drMerkleRoot,
_index,
_element));
}
/// @dev Verifies the validity of a PoI against the tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the element
/// @return true or false depending the validity
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot;
return(verifyPoi(
_poi,
tallyMerkleRoot,
_index,
_element));
}
/// @dev Verifies if the contract is upgradable
/// @return true if the contract upgradable
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Post new block into the block relay
/// @param _blockHash Hash of the block header
/// @param _epoch Witnet epoch to which the block belongs to
/// @param _drMerkleRoot Merkle root belonging to the data requests
/// @param _tallyMerkleRoot Merkle root belonging to the tallies
function postNewBlock(
uint256 _blockHash,
uint256 _epoch,
uint256 _drMerkleRoot,
uint256 _tallyMerkleRoot)
external
isOwner
blockDoesNotExist(_blockHash)
{
lastBlock.blockHash = _blockHash;
lastBlock.epoch = _epoch;
blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot;
blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot;
emit NewBlock(witnet, _blockHash);
}
/// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header
/// @return Requests-only merkle root hash in the block header.
function readDrMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].drHashMerkleRoot;
}
/// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header.
/// @return tallies-only merkle root hash in the block header.
function readTallyMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].tallyHashMerkleRoot;
}
/// @dev Verifies the validity of a PoI
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _root the merkle root
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyPoi(
uint256[] memory _poi,
uint256 _root,
uint256 _index,
uint256 _element)
private pure returns(bool)
{
uint256 tree = _element;
uint256 index = _index;
// We want to prove that the hash of the _poi and the _element is equal to _root
// For knowing if concatenate to the left or the right we check the parity of the the index
for (uint i = 0; i < _poi.length; i++) {
if (index%2 == 0) {
tree = uint256(sha256(abi.encodePacked(tree, _poi[i])));
} else {
tree = uint256(sha256(abi.encodePacked(_poi[i], tree)));
}
index = index >> 1;
}
return _root == tree;
}
}
// File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay
* @dev More information can be found here
* DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks
* @author Witnet Foundation
*/
contract BlockRelayProxy {
// Address of the current controller
address internal blockRelayAddress;
// Current interface to the controller
BlockRelayInterface internal blockRelayInstance;
struct ControllerInfo {
// last epoch seen by a controller
uint256 lastEpoch;
// address of the controller
address blockRelayController;
}
// array containing the information about controllers
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use");
_;
}
constructor(address _blockRelayAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress}));
blockRelayAddress = _blockRelayAddress;
blockRelayInstance = BlockRelayInterface(_blockRelayAddress);
}
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory) {
return blockRelayInstance.getLastBeacon();
}
/// @notice Returns the last Wtinet epoch known to the block relay instance.
/// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request.
function getLastEpoch() external view returns(uint256) {
return blockRelayInstance.getLastEpoch();
}
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyDrPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Verifies the validity of a tally PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyTallyPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Upgrades the block relay if the current one is upgradeable
/// @param _newAddress address of the new block relay to upgrade
function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) {
// Check if the controller is upgradeable
require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Get last epoch seen by the replaced controller
uint256 epoch = blockRelayInstance.getLastEpoch();
// Get the length of last epochs seen by the different controllers
uint256 n = controllers.length;
// If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0
// just update the already anotated epoch with the new address, ignoring the previously inserted controller
// Else, anotate the epoch from which the new controller should start receiving blocks
if (epoch < controllers[n-1].lastEpoch) {
controllers[n-1].blockRelayController = _newAddress;
} else {
controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress}));
}
// Update instance
blockRelayAddress = _newAddress;
blockRelayInstance = BlockRelayInterface(_newAddress);
}
/// @notice Gets the controller associated with the BR controller corresponding to the epoch provided
/// @param _epoch the epoch to work with
function getController(uint256 _epoch) public view returns(address _controller) {
// Get length of all last epochs seen by controllers
uint256 n = controllers.length;
// Go backwards until we find the controller having that blockhash
for (uint i = n; i > 0; i--) {
if (_epoch >= controllers[i-1].lastEpoch) {
return (controllers[i-1].blockRelayController);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: elliptic-curve-solidity/contracts/EllipticCurve.sol
/**
* @title Elliptic Curve Library
* @dev Library providing arithmetic operations over elliptic curves.
* @author Witnet Foundation
*/
library EllipticCurve {
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 newR = _x;
uint256 t;
while (newR != 0) {
t = r / newR;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, newR) = (newR, r - t * newR );
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) {
require(_pp!=0, "Modulus is zero");
if (_base == 0)
return 0;
if (_exp == 0)
return 1;
uint256 r = 1;
uint256 bit = 2 ** 255;
assembly {
for { } gt(bit, 0) { }{
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp)
internal pure returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp)
internal pure returns (uint256)
{
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
// x^3 + ax + b
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp)
internal pure returns (bool)
{
if (0 == _x || _x == _pp || 0 == _y || _y == _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp)
internal pure returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1==_x2) {
(x, y, z) = jacDouble(
_x1,
_y1,
1,
_aa,
_pp);
} else {
(x, y, z) = jacAdd(
_x1,
_y1,
1,
_x2,
_y2,
1,
_pp);
}
// Get back to affine
return toAffine(
x,
y,
z,
_pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(
_x1,
_y1,
x,
y,
_aa,
_pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(
_k,
_x,
_y,
1,
_aa,
_pp);
// Get back to affine
return toAffine(
x1,
y1,
z1,
_pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if ((_x1==0)&&(_y1==0))
return (_x2, _y2, _z2);
if ((_x2==0)&&(_y2==0))
return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(zs[0] != zs[2], "Invalid data");
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return(qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _pp the modulus
/// @param _aa the a scalar in the curve equation
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if (_z == 0)
return (_x, _y, _z);
uint256[3] memory square;
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
square[0] = mulmod(_x, _x, _pp); //x1^2
square[1] = mulmod(_y, _y, _pp); //y1^2
square[2] = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp);
// m
uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp);
// qx
uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp);
// qz = 2*y1*z1
uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
uint256 remaining = _d;
uint256[3] memory point;
point[0] = _x;
point[1] = _y;
point[2] = _z;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
if (_d == 0) {
return (qx, qy, qz);
}
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(
qx,
qy,
qz,
point[0],
point[1],
point[2],
_pp);
}
remaining = remaining / 2;
(point[0], point[1], point[2]) = jacDouble(
point[0],
point[1],
point[2],
_aa,
_pp);
}
return (qx, qy, qz);
}
}
// File: vrf-solidity/contracts/VRF.sol
/**
* @title Verifiable Random Functions (VRF)
* @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function.
* @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979).
* It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve.
* @author Witnet Foundation
*/
library VRF {
/**
* Secp256k1 parameters
*/
// Generator coordinate `x` of the EC curve
uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
// Generator coordinate `y` of the EC curve
uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Constant `a` of EC equation
uint256 public constant AA = 0;
// Constant `b` of EC equation
uint256 public constant BB = 7;
// Prime number of the curve
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Order of the curve
uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev Public key derivation from private key.
/// @param _d The scalar
/// @param _x The coordinate x
/// @param _y The coordinate y
/// @return (qx, qy) The derived point
function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) {
return EllipticCurve.ecMul(
_d,
_x,
_y,
AA,
PP
);
}
/// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`).
/// @param _yByte The parity byte following the ec point compressed format
/// @param _x The coordinate `x` of the point
/// @return The coordinate `y` of the point
function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) {
return EllipticCurve.deriveY(
_yByte,
_x,
AA,
BB,
PP);
}
/// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix
/// concatenated with the gamma point
/// @param _gammaX The x-coordinate of the gamma EC point
/// @param _gammaY The y-coordinate of the gamma EC point
/// @return The VRF hash ouput as shas256 digest
function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) {
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(0xFE),
// 0x01
uint8(0x03),
// Compressed Gamma Point
encodePoint(_gammaX, _gammaY));
return sha256(c);
}
/// @dev VRF verification by providing the public key, the message and the VRF proof.
/// This function computes several elliptic curve operations which may lead to extensive gas consumption.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return true, if VRF proof is valid
function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) {
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3: U = s*B - c*Y (where B is the generator)
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Step 4: V = s*H - c*Gamma
(uint256 vPointX, uint256 vPointY) = ecMulSubMul(
_proof[3],
hPoint[0],
hPoint[1],
_proof[2],
_proof[0],_proof[1]);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
uPointX,
uPointY,
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut.
/// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @param _uPoint The `u` EC point defined as `U = s*B - c*Y`
/// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma`
/// @return true, if VRF proof is valid
function fastVerify(
uint256[2] memory _publicKey,
uint256[4] memory _proof,
bytes memory _message,
uint256[2] memory _uPoint,
uint256[4] memory _vComponents)
internal pure returns (bool)
{
// Step 2: Hash to try and increment -> hashed value, a finite EC point in G
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3 & Step 4:
// U = s*B - c*Y (where B is the generator)
// V = s*H - c*Gamma
if (!ecMulSubMulVerify(
_proof[3],
_proof[2],
_publicKey[0],
_publicKey[1],
_uPoint[0],
_uPoint[1]) ||
!ecMulVerify(
_proof[3],
hPoint[0],
hPoint[1],
_vComponents[0],
_vComponents[1]) ||
!ecMulVerify(
_proof[2],
_proof[0],
_proof[1],
_vComponents[2],
_vComponents[3])
)
{
return false;
}
(uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub(
_vComponents[0],
_vComponents[1],
_vComponents[2],
_vComponents[3],
AA,
PP);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
_uPoint[0],
_uPoint[1],
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev Decode VRF proof from bytes
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) {
require(_proof.length == 81, "Malformed VRF proof");
uint8 gammaSign;
uint256 gammaX;
uint128 c;
uint256 s;
assembly {
gammaSign := mload(add(_proof, 1))
gammaX := mload(add(_proof, 33))
c := mload(add(_proof, 49))
s := mload(add(_proof, 81))
}
uint256 gammaY = deriveY(gammaSign, gammaX);
return [
gammaX,
gammaY,
c,
s];
}
/// @dev Decode EC point from bytes
/// @param _point The EC point as bytes
/// @return The point as `[point-x, point-y]`
function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) {
require(_point.length == 33, "Malformed compressed EC point");
uint8 sign;
uint256 x;
assembly {
sign := mload(add(_point, 1))
x := mload(add(_point, 33))
}
uint256 y = deriveY(sign, x);
return [x, y];
}
/// @dev Compute the parameters (EC points) required for the VRF fast verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`
function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message)
internal pure returns (uint256[2] memory, uint256[4] memory)
{
// Requirements for Step 3: U = s*B - c*Y (where B is the generator)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Requirements for Step 4: V = s*H - c*Gamma
(uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]);
(uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]);
return (
[uPointX, uPointY],
[
sHX,
sHY,
cGammaX,
cGammaY
]);
}
/// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 2 of VRF verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _message The message used for computing the VRF
/// @return The hash point in affine cooridnates
function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) {
// Step 1: public key to bytes
// Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(254),
// 0x01
uint8(1),
// Public Key
encodePoint(_publicKey[0], _publicKey[1]),
// Message
_message);
// Step 3: find a valid EC point
// Loop over counter ctr starting at 0x00 and do hash
for (uint8 ctr = 0; ctr < 256; ctr++) {
// Counter update
// c[cLength-1] = byte(ctr);
bytes32 sha = sha256(abi.encodePacked(c, ctr));
// Step 4: arbitraty string to point and check if it is on curve
uint hPointX = uint256(sha);
uint hPointY = deriveY(2, hPointX);
if (EllipticCurve.isOnCurve(
hPointX,
hPointY,
AA,
BB,
PP))
{
// Step 5 (omitted): calculate H (cofactor is 1 on secp256k1)
// If H is not "INVALID" and cofactor > 1, set H = cofactor * H
return (hPointX, hPointY);
}
}
revert("No valid point was found");
}
/// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 5 of VRF verification function.
/// @param _hPointX The coordinate `x` of point `H`
/// @param _hPointY The coordinate `y` of point `H`
/// @param _gammaX The coordinate `x` of the point `Gamma`
/// @param _gammaX The coordinate `y` of the point `Gamma`
/// @param _uPointX The coordinate `x` of point `U`
/// @param _uPointY The coordinate `y` of point `U`
/// @param _vPointX The coordinate `x` of point `V`
/// @param _vPointY The coordinate `y` of point `V`
/// @return The first half of the digest of the points using SHA256
function hashPoints(
uint256 _hPointX,
uint256 _hPointY,
uint256 _gammaX,
uint256 _gammaY,
uint256 _uPointX,
uint256 _uPointY,
uint256 _vPointX,
uint256 _vPointY)
internal pure returns (bytes16)
{
bytes memory c = abi.encodePacked(
// Ciphersuite 0xFE
uint8(254),
// Prefix 0x02
uint8(2),
// Points to Bytes
encodePoint(_hPointX, _hPointY),
encodePoint(_gammaX, _gammaY),
encodePoint(_uPointX, _uPointY),
encodePoint(_vPointX, _vPointY)
);
// Hash bytes and truncate
bytes32 sha = sha256(c);
bytes16 half1;
assembly {
let freemem_pointer := mload(0x40)
mstore(add(freemem_pointer,0x00), sha)
half1 := mload(add(freemem_pointer,0x00))
}
return half1;
}
/// @dev Encode an EC point to bytes
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The point coordinates as bytes
function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) {
uint8 prefix = uint8(2 + (_y % 2));
return abi.encodePacked(prefix, _x);
}
/// @dev Substracts two key derivation functionsas `s1*A - s2*B`.
/// @param _scalar1 The scalar `s1`
/// @param _a1 The `x` coordinate of point `A`
/// @param _a2 The `y` coordinate of point `A`
/// @param _scalar2 The scalar `s2`
/// @param _b1 The `x` coordinate of point `B`
/// @param _b2 The `y` coordinate of point `B`
/// @return The derived point in affine cooridnates
function ecMulSubMul(
uint256 _scalar1,
uint256 _a1,
uint256 _a2,
uint256 _scalar2,
uint256 _b1,
uint256 _b2)
internal pure returns (uint256, uint256)
{
(uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2);
(uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2);
(uint256 r1, uint256 r2) = EllipticCurve.ecSub(
m1,
m2,
n1,
n2,
AA,
PP);
return (r1, r2);
}
/// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _scalar The scalar of the point multiplication
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @param _qx The coordinate `x` of the multiplication result
/// @param _qy The coordinate `y` of the multiplication result
/// @return true, if first 20 bytes match
function ecMulVerify(
uint256 _scalar,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
address result = ecrecover(
0,
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(_scalar, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on SolCrypto library: https://github.com/HarryR/solcrypto
/// @param _scalar1 The scalar of the multiplication of `(gx,gy)`
/// @param _scalar2 The scalar of the multiplication of `(x,y)`
/// @param _x The coordinate `x` of the point to be mutiply by `scalar2`
/// @param _y The coordinate `y` of the point to be mutiply by `scalar2`
/// @param _qx The coordinate `x` of the equation result
/// @param _qy The coordinate `y` of the equation result
/// @return true, if first 20 bytes match
function ecMulSubMulVerify(
uint256 _scalar1,
uint256 _scalar2,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
uint256 scalar1 = (NN - _scalar1) % NN;
scalar1 = mulmod(scalar1, _x, NN);
uint256 scalar2 = (NN - _scalar2) % NN;
address result = ecrecover(
bytes32(scalar1),
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(scalar2, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest.
/// This function is used for performing a fast EC multiplication verification.
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The address of the EC point digest (keccak256)
function pointToAddress(uint256 _x, uint256 _y)
internal pure returns(address)
{
return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
// File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol
/**
* @title Active Bridge Set (ABS) library
* @notice This library counts the number of bridges that were active recently.
*/
library ActiveBridgeSetLib {
// Number of Ethereum blocks during which identities can be pushed into a single activity slot
uint8 public constant CLAIM_BLOCK_PERIOD = 8;
// Number of activity slots in the ABS
uint8 public constant ACTIVITY_LENGTH = 100;
struct ActiveBridgeSet {
// Mapping of activity slots with participating identities
mapping (uint16 => address[]) epochIdentities;
// Mapping of identities with their participation count
mapping (address => uint16) identityCount;
// Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`)
uint32 activeIdentities;
// Number of identities for the next activity slot (to be updated in the next activity slot)
uint32 nextActiveIdentities;
// Last used block number during an activity update
uint256 lastBlockNumber;
}
modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) {
require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block");
_;
}
/// @dev Updates activity in Witnet without requiring protocol participation.
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _blockNumber The block number up to which the activity should be updated.
function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Avoid gas cost if ABS is up to date
require(
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
), "The ABS was already up to date");
_abs.lastBlockNumber = _blockNumber;
}
/// @dev Pushes activity updates through protocol activities (implying insertion of identity).
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _address The address pushing the activity.
/// @param _blockNumber The block number up to which the activity should be updated.
function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
returns (bool success)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Update ABS and if it was already up to date, check if identities already counted
if (
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
))
{
_abs.lastBlockNumber = _blockNumber;
} else {
// Check if address was already counted as active identity in this current activity slot
uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length;
for (uint256 i; i < epochIdsLength; i++) {
if (_abs.epochIdentities[currentSlot][i] == _address) {
return false;
}
}
}
// Update current activity slot with identity:
// 1. Add currentSlot to `epochIdentities` with address
// 2. If count = 0, increment by 1 `nextActiveIdentities`
// 3. Increment by 1 the count of the identity
_abs.epochIdentities[currentSlot].push(_address);
if (_abs.identityCount[_address] == 0) {
_abs.nextActiveIdentities++;
}
_abs.identityCount[_address]++;
return true;
}
/// @dev Checks if an address is a member of the ABS.
/// @param _abs The Active Bridge Set structure from the Witnet Requests Board.
/// @param _address The address to check.
/// @return true if address is member of ABS.
function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) {
return _abs.identityCount[_address] > 0;
}
/// @dev Gets the slots of the last block seen by the ABS provided and the block number provided.
/// @param _abs The Active Bridge Set structure containing the last block.
/// @param _blockNumber The block number from which to get the current slot.
/// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference > CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH.
function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) {
// Get current activity slot number
uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Get last actitivy slot number
uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Check if there was an activity slot overflow
// `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently
bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH);
return (currentSlot, lastSlot, overflow);
}
/// @dev Updates the provided ABS according to the slots provided.
/// @param _abs The Active Bridge Set to be updated.
/// @param _currentSlot The current slot.
/// @param _lastSlot The last slot seen by the ABS.
/// @param _overflow Whether the current slot has overflown the last slot.
/// @return True if update occurred.
function updateABS(
ActiveBridgeSet storage _abs,
uint16 _currentSlot,
uint16 _lastSlot,
bool _overflow)
private
returns (bool)
{
// If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS
if (_overflow) {
flushABS(_abs, _lastSlot, _lastSlot);
// If ABS are not up to date => fill previous activity slots with empty activities
} else if (_currentSlot != _lastSlot) {
flushABS(_abs, _currentSlot, _lastSlot);
} else {
return false;
}
return true;
}
/// @dev Flushes the provided ABS record between lastSlot and currentSlot.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _currentSlot The current slot.
function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private {
// For each slot elapsed, remove identities and update `nextActiveIdentities` count
for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) {
flushSlot(_abs, slot);
}
// Update current activity slot
flushSlot(_abs, _currentSlot);
_abs.activeIdentities = _abs.nextActiveIdentities;
}
/// @dev Flushes a slot of the provided ABS.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _slot The slot to be flushed.
function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private {
// For a given slot, go through all identities to flush them
uint256 epochIdsLength = _abs.epochIdentities[_slot].length;
for (uint256 id = 0; id < epochIdsLength; id++) {
flushIdentity(_abs, _abs.epochIdentities[_slot][id]);
}
delete _abs.epochIdentities[_slot];
}
/// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _address The address to be flushed.
function flushIdentity(ActiveBridgeSet storage _abs, address _address) private {
require(absMembership(_abs, _address), "The identity address is already out of the ARS");
// Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count
_abs.identityCount[_address]--;
if (_abs.identityCount[_address] == 0) {
delete _abs.identityCount[_address];
_abs.nextActiveIdentities--;
}
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol
/**
* @title Witnet Requests Board Interface
* @notice Interface of a Witnet Request Board (WRB)
* It defines how to interact with the WRB in order to support:
* - Post and upgrade a data request
* - Read the result of a dr
* @author Witnet Foundation
*/
interface WitnetRequestsBoardInterface {
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256);
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable;
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR
function readDrHash (uint256 _id) external view returns(uint256);
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult (uint256 _id) external view returns(bytes memory);
/// @notice Verifies if the block relay can be upgraded.
/// @return true if contract is upgradable.
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol
/**
* @title Witnet Requests Board
* @notice Contract to bridge requests to Witnet.
* @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
* The result of the requests will be posted back to this contract by the bridge nodes too.
* @author Witnet Foundation
*/
contract WitnetRequestsBoard is WitnetRequestsBoardInterface {
using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet;
// Expiration period after which a Witnet Request can be claimed again
uint256 public constant CLAIM_EXPIRATION = 13;
struct DataRequest {
bytes dr;
uint256 inclusionReward;
uint256 tallyReward;
bytes result;
// Block number at which the DR was claimed for the last time
uint256 blockNumber;
uint256 drHash;
address payable pkhClaim;
}
// Owner of the Witnet Request Board
address public witnet;
// Block Relay proxy prividing verification functions
BlockRelayProxy public blockRelay;
// Witnet Requests within the board
DataRequest[] public requests;
// Set of recently active bridges
ActiveBridgeSetLib.ActiveBridgeSet public abs;
// Replication factor for Active Bridge Set identities
uint8 public repFactor;
// Event emitted when a new DR is posted
event PostedRequest(address indexed _from, uint256 _id);
// Event emitted when a DR inclusion proof is posted
event IncludedRequest(address indexed _from, uint256 _id);
// Event emitted when a result proof is posted
event PostedResult(address indexed _from, uint256 _id);
// Ensures the reward is not greater than the value
modifier payingEnough(uint256 _value, uint256 _tally) {
require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward");
_;
}
// Ensures the poe is valid
modifier poeValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) {
require(
verifyPoe(
_poe,
_publicKey,
_uPoint,
_vPointHelpers),
"Not a valid PoE");
_;
}
// Ensures signature (sign(msg.sender)) is valid
modifier validSignature(
uint256[2] memory _publicKey,
bytes memory addrSignature) {
require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature");
_;
}
// Ensures the DR inclusion proof has not been reported yet
modifier drNotIncluded(uint256 _id) {
require(requests[_id].drHash == 0, "DR already included");
_;
}
// Ensures the DR inclusion has been already reported
modifier drIncluded(uint256 _id) {
require(requests[_id].drHash != 0, "DR not yet included");
_;
}
// Ensures the result has not been reported yet
modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
// Ensures the VRF is valid
modifier vrfValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) virtual {
require(
VRF.fastVerify(
_publicKey,
_poe,
getLastBeacon(),
_uPoint,
_vPointHelpers),
"Not a valid VRF");
_;
}
// Ensures the address belongs to the active bridge set
modifier absMember(address _address) {
require(abs.absMembership(_address), "Not a member of the ABS");
_;
}
/**
* @notice Include an address to specify the Witnet Block Relay and a replication factor.
* @param _blockRelayAddress BlockRelayProxy address.
* @param _repFactor replication factor.
*/
constructor(address _blockRelayAddress, uint8 _repFactor) public {
blockRelay = BlockRelayProxy(_blockRelayAddress);
witnet = msg.sender;
// Insert an empty request so as to initialize the requests array with length > 0
DataRequest memory request;
requests.push(request);
repFactor = _repFactor;
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
override
returns(uint256)
{
// The initial length of the `requests` array will become the ID of the request for everything related to the WRB
uint256 id = requests.length;
// Create a new `DataRequest` object and initialize all the non-default fields
DataRequest memory request;
request.dr = _serialized;
request.inclusionReward = SafeMath.sub(msg.value, _tallyReward);
request.tallyReward = _tallyReward;
// Push the new request into the contract state
requests.push(request);
// Let observers know that a new request has been posted
emit PostedRequest(msg.sender, id);
return id;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
resultNotIncluded(_id)
override
{
if (requests[_id].drHash != 0) {
require(
msg.value == _tallyReward,
"Txn value should equal result reward argument (request reward already paid)"
);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
} else {
requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
}
}
/// @dev Checks if the data requests from a list are claimable or not.
/// @param _ids The list of data request identifiers to be checked.
/// @return An array of booleans indicating if data requests are claimable or not.
function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) {
uint256 idsLength = _ids.length;
bool[] memory validIds = new bool[](idsLength);
for (uint i = 0; i < idsLength; i++) {
uint256 index = _ids[i];
validIds[i] = (dataRequestCanBeClaimed(requests[index])) &&
requests[index].drHash == 0 &&
index < requests.length &&
requests[index].result.length == 0;
}
return validIds;
}
/// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash).
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet.
/// @param _index The index in the merkle tree.
/// @param _blockHash The hash of the block in which the data request was inserted.
/// @param _epoch The epoch in which the blockHash was created.
function reportDataRequestInclusion(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch)
external
drNotIncluded(_id)
{
// Check the data request has been claimed
require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed");
uint256 drOutputHash = uint256(sha256(requests[_id].dr));
uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0])));
// Update the state upon which this function depends before the external call
requests[_id].drHash = drHash;
require(
blockRelay.verifyDrPoi(
_poi,
_blockHash,
_epoch,
_index,
drOutputHash), "Invalid PoI");
requests[_id].pkhClaim.transfer(requests[_id].inclusionReward);
// Push requests[_id].pkhClaim to abs
abs.pushActivity(requests[_id].pkhClaim, block.number);
emit IncludedRequest(msg.sender, _id);
}
/// @dev Reports the result of a data request in Witnet.
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block.
/// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block.
/// @param _blockHash The hash of the block in which the result (tally) was inserted.
/// @param _epoch The epoch in which the blockHash was created.
/// @param _result The result itself as bytes.
function reportResult(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch,
bytes calldata _result)
external
drIncluded(_id)
resultNotIncluded(_id)
absMember(msg.sender)
{
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_result.length != 0, "Result has zero length");
// Update the state upon which this function depends before the external call
requests[_id].result = _result;
uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result)));
require(
blockRelay.verifyTallyPoi(
_poi,
_blockHash,
_epoch,
_index,
resHash), "Invalid PoI");
msg.sender.transfer(requests[_id].tallyReward);
emit PostedResult(msg.sender, _id);
}
/// @dev Retrieves the bytes of the serialization of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the data request as bytes.
function readDataRequest(uint256 _id) external view returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].dr;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
/// @dev Retrieves hash of the data request transaction in Witnet.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DataRequest transaction in Witnet.
function readDrHash(uint256 _id) external view override returns(uint256) {
require(requests.length > _id, "Id not found");
return requests[_id].drHash;
}
/// @dev Returns the number of data requests in the WRB.
/// @return the number of data requests in the WRB.
function requestsCount() external view returns(uint256) {
return requests.length;
}
/// @notice Wrapper around the decodeProof from VRF library.
/// @dev Decode VRF proof from bytes.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) {
return VRF.decodeProof(_proof);
}
/// @notice Wrapper around the decodePoint from VRF library.
/// @dev Decode EC point from bytes.
/// @param _point The EC point as bytes.
/// @return The point as `[point-x, point-y]`.
function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) {
return VRF.decodePoint(_point);
}
/// @dev Wrapper around the computeFastVerifyParams from VRF library.
/// @dev Compute the parameters (EC points) required for the VRF fast verification function..
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @param _message The message (in bytes) used for computing the VRF.
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`.
function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message)
external pure returns (uint256[2] memory, uint256[4] memory)
{
return VRF.computeFastVerifyParams(_publicKey, _proof, _message);
}
/// @dev Updates the ABS activity with the block number provided.
/// @param _blockNumber update the ABS until this block number.
function updateAbsActivity(uint256 _blockNumber) external {
require (_blockNumber <= block.number, "The provided block number has not been reached");
abs.updateActivity(_blockNumber);
}
/// @dev Verifies if the contract is upgradable.
/// @return true if the contract upgradable.
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _ids Data request ids to be claimed.
/// @param _poe PoE claiming eligibility.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function claimDataRequests(
uint256[] memory _ids,
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers,
bytes memory addrSignature)
public
validSignature(_publicKey, addrSignature)
poeValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
for (uint i = 0; i < _ids.length; i++) {
require(
dataRequestCanBeClaimed(requests[_ids[i]]),
"One of the listed data requests was already claimed"
);
requests[_ids[i]].pkhClaim = msg.sender;
requests[_ids[i]].blockNumber = block.number;
}
return true;
}
/// @dev Read the beacon of the last block inserted.
/// @return bytes to be signed by the node as PoE.
function getLastBeacon() public view virtual returns(bytes memory) {
return blockRelay.getLastBeacon();
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _poe PoE claiming eligibility.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function verifyPoe(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers)
internal
view
vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1]));
// True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities
if (abs.activeIdentities < repFactor) {
return true;
}
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency
if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) {
return true;
}
return false;
}
/// @dev Verifies the validity of a signature.
/// @param _message message to be verified.
/// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`.
/// @param _addrSignature the signature to verify asas r||s||v.
/// @return true or false depending the validity.
function verifySig(
bytes memory _message,
uint256[2] memory _publicKey,
bytes memory _addrSignature)
internal
pure
returns(bool)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_addrSignature, 0x20))
s := mload(add(_addrSignature, 0x40))
v := byte(0, mload(add(_addrSignature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return false;
}
if (v != 0 && v != 1) {
return false;
}
v = 28 - v;
bytes32 msgHash = sha256(_message);
address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]);
return ecrecover(
msgHash,
v,
r,
s) == hashedKey;
}
function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) {
return
(_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) &&
_request.drHash == 0 &&
_request.result.length == 0;
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay.
* @author Witnet Foundation
*/
contract WitnetRequestsBoardProxy {
// Address of the Witnet Request Board contract that is currently being used
address public witnetRequestsBoardAddress;
// Struct if the information of each controller
struct ControllerInfo {
// Address of the Controller
address controllerAddress;
// The lastId of the previous Controller
uint256 lastId;
}
// Last id of the WRB controller
uint256 internal currentLastId;
// Instance of the current WitnetRequestBoard
WitnetRequestsBoardInterface internal witnetRequestsBoardInstance;
// Array with the controllers that have been used in the Proxy
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use");
_;
}
/**
* @notice Include an address to specify the Witnet Request Board.
* @param _witnetRequestsBoardAddress WitnetRequestBoard address.
*/
constructor(address _witnetRequestsBoardAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0}));
witnetRequestsBoardAddress = _witnetRequestsBoardAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress);
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) {
uint256 n = controllers.length;
uint256 offset = controllers[n - 1].lastId;
// Update the currentLastId with the id in the controller plus the offSet
currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset;
return currentLastId;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable {
address wrbAddress;
uint256 wrbOffset;
(wrbAddress, wrbOffset) = getController(_id);
return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward);
}
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR.
function readDrHash (uint256 _id)
external
view
returns(uint256)
{
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offsetWrb;
(wrbAddress, offsetWrb) = getController(_id);
// Return the result of the DR readed in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithDrHash;
wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress);
uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb);
return drHash;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR.
function readResult(uint256 _id) external view returns(bytes memory) {
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offSetWrb;
(wrbAddress, offSetWrb) = getController(_id);
// Return the result of the DR in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithResult;
wrbWithResult = WitnetRequestsBoardInterface(wrbAddress);
return wrbWithResult.readResult(_id - offSetWrb);
}
/// @notice Upgrades the Witnet Requests Board if the current one is upgradeable.
/// @param _newAddress address of the new block relay to upgrade.
function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) {
// Require the WRB is upgradable
require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers
controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId}));
// Upgrade the WRB
witnetRequestsBoardAddress = _newAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress);
}
/// @notice Gets the controller from an Id.
/// @param _id id of a Data Request from which we get the controller.
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
}
// File: witnet-ethereum-bridge/contracts/BufferLib.sol
/**
* @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface
* @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will
* start with the byte that goes right after the last one in the previous read.
* @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some
* theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.
*/
library BufferLib {
struct Buffer {
bytes data;
uint32 cursor;
}
// Ensures we access an existing index in an array
modifier notOutOfBounds(uint32 index, uint256 length) {
require(index < length, "Tried to read from a consumed Buffer (must rewind it first)");
_;
}
/**
* @notice Read and consume a certain amount of bytes from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _length How many bytes to read and consume from the buffer.
* @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position.
*/
function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) {
// Make sure not to read out of the bounds of the original bytes
require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading");
// Create a new `bytes memory destination` value
bytes memory destination = new bytes(_length);
bytes memory source = _buffer.data;
uint32 offset = _buffer.cursor;
// Get raw pointers for source and destination
uint sourcePointer;
uint destinationPointer;
assembly {
sourcePointer := add(add(source, 32), offset)
destinationPointer := add(destination, 32)
}
// Copy `_length` bytes from source to destination
memcpy(destinationPointer, sourcePointer, uint(_length));
// Move the cursor forward by `_length` bytes
seek(_buffer, _length, true);
return destination;
}
/**
* @notice Read and consume the next byte from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The next byte in the buffer counting from the cursor position.
*/
function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) {
// Return the byte at the position marked by the cursor and advance the cursor all at once
return _buffer.data[_buffer.cursor++];
}
/**
* @notice Move the inner cursor of the buffer to a relative or absolute position.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _offset How many bytes to move the cursor forward.
* @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the
* buffer (`true`).
* @return The final position of the cursor (will equal `_offset` if `_relative` is `false`).
*/
// solium-disable-next-line security/no-assign-params
function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) {
// Deal with relative offsets
if (_relative) {
require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking");
_offset += _buffer.cursor;
}
// Make sure not to read out of the bounds of the original bytes
require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking");
_buffer.cursor = _offset;
return _buffer.cursor;
}
/**
* @notice Move the inner cursor a number of bytes forward.
* @dev This is a simple wrapper around the relative offset case of `seek()`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _relativeOffset How many bytes to move the cursor forward.
* @return The final position of the cursor.
*/
function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) {
return seek(_buffer, _relativeOffset, true);
}
/**
* @notice Move the inner cursor back to the first byte in the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function rewind(Buffer memory _buffer) internal pure {
_buffer.cursor = 0;
}
/**
* @notice Read and consume the next byte from the buffer as an `uint8`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint8` value of the next byte in the buffer counting from the cursor position.
*/
function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an `uint16`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.
*/
function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint16 value;
assembly {
value := mload(add(add(bytesValue, 2), offset))
}
_buffer.cursor += 2;
return value;
}
/**
* @notice Read and consume the next 4 bytes from the buffer as an `uint32`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint32 value;
assembly {
value := mload(add(add(bytesValue, 4), offset))
}
_buffer.cursor += 4;
return value;
}
/**
* @notice Read and consume the next 8 bytes from the buffer as an `uint64`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.
*/
function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint64 value;
assembly {
value := mload(add(add(bytesValue, 8), offset))
}
_buffer.cursor += 8;
return value;
}
/**
* @notice Read and consume the next 16 bytes from the buffer as an `uint128`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
*/
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
/**
* @notice Read and consume the next 32 bytes from the buffer as an `uint256`.
* @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an
* `int32`.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`
* use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are
* expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readFloat16(Buffer memory _buffer) internal pure returns (int32) {
uint32 bytesValue = readUint16(_buffer);
// Get bit at position 0
uint32 sign = bytesValue & 0x8000;
// Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias
int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15;
// Get bits 6 to 15
int32 significand = int32(bytesValue & 0x03ff);
// Add 1024 to the fraction if the exponent is 0
if (exponent == 15) {
significand |= 0x400;
}
// Compute `2 ^ exponent Β· (1 + fraction / 1024)`
int32 result = 0;
if (exponent >= 0) {
result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10);
} else {
result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10);
}
// Make the result negative if the sign bit is not 0
if (sign != 0) {
result *= - 1;
}
return result;
}
/**
* @notice Copy bytes from one memory address into another.
* @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms
* of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).
* @param _dest Address of the destination memory.
* @param _src Address to the source memory.
* @param _len How many bytes to copy.
*/
// solium-disable-next-line security/no-assign-params
function memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
}
// File: witnet-ethereum-bridge/contracts/CBOR.sol
/**
* @title A minimalistic implementation of βRFC 7049 Concise Binary Object Representationβ
* @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize
* the gas cost of decoding them into a useful native type.
* @dev Most of the logic has been borrowed from Patrick Ganstererβs cbor.js library: https://github.com/paroga/cbor-js
* TODO: add support for Array (majorType = 4)
* TODO: add support for Map (majorType = 5)
* TODO: add support for Float32 (majorType = 7, additionalInformation = 26)
* TODO: add support for Float64 (majorType = 7, additionalInformation = 27)
*/
library CBOR {
using BufferLib for BufferLib.Buffer;
uint64 constant internal UINT64_MAX = ~uint64(0);
struct Value {
BufferLib.Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `bytes` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `bytes` value.
*/
function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory bytesData;
// These checks look repetitive but the equivalent loop would be more expensive.
uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
}
}
return bytesData;
} else {
return _cborValue.buffer.read(uint32(_cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a `fixed16` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeFixed16(Value memory _cborValue) public pure returns(int32) {
require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7");
require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25");
return _cborValue.buffer.readFloat16();
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention.
* as explained in `decodeFixed16`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeFixed16(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeInt128(Value memory _cborValue) public pure returns(int128) {
if (_cborValue.majorType == 1) {
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
return int128(-1) - int128(length);
} else if (_cborValue.majorType == 0) {
// Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer
// a uniform API for positive and negative numbers
return int128(decodeUint64(_cborValue));
}
revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1");
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeInt128(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `string` value.
*/
function decodeString(Value memory _cborValue) public pure returns(string memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory textData;
bool done;
while (!done) {
uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType);
if (itemLength < UINT64_MAX) {
textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4));
} else {
done = true;
}
}
return string(textData);
} else {
return string(readText(_cborValue.buffer, _cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `string[]` value.
*/
function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) {
require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
string[] memory array = new string[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeString(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64` value.
*/
function decodeUint64(Value memory _cborValue) public pure returns(uint64) {
require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0");
return readLength(_cborValue.buffer, _cborValue.additionalInformation);
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64[]` value.
*/
function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) {
require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
uint64[] memory array = new uint64[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeUint64(item);
}
return array;
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) {
BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0);
return valueFromBuffer(buffer);
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _buffer A Buffer structure representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) {
require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value");
uint8 initialByte;
uint8 majorType = 255;
uint8 additionalInformation;
uint64 length;
uint64 tag = UINT64_MAX;
bool isTagged = true;
while (isTagged) {
// Extract basic CBOR properties from input bytes
initialByte = _buffer.readUint8();
majorType = initialByte >> 5;
additionalInformation = initialByte & 0x1f;
// Early CBOR tag parsing.
if (majorType == 6) {
tag = readLength(_buffer, additionalInformation);
} else {
isTagged = false;
}
}
require(majorType <= 7, "Invalid CBOR major type");
return CBOR.Value(
_buffer,
initialByte,
majorType,
additionalInformation,
length,
tag);
}
// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the
// value of the `additionalInformation` argument.
function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) {
if (additionalInformation < 24) {
return additionalInformation;
}
if (additionalInformation == 24) {
return _buffer.readUint8();
}
if (additionalInformation == 25) {
return _buffer.readUint16();
}
if (additionalInformation == 26) {
return _buffer.readUint32();
}
if (additionalInformation == 27) {
return _buffer.readUint64();
}
if (additionalInformation == 31) {
return UINT64_MAX;
}
revert("Invalid length encoding (non-existent additionalInformation value)");
}
// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming
// as many bytes as specified by the first byte.
function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) {
uint8 initialByte = _buffer.readUint8();
if (initialByte == 0xff) {
return UINT64_MAX;
}
uint64 length = readLength(_buffer, initialByte & 0x1f);
require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length");
return length;
}
// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,
// but it can be easily casted into a string with `string(result)`.
// solium-disable-next-line security/no-assign-params
function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) {
bytes memory result;
for (uint64 index = 0; index < _length; index++) {
uint8 value = _buffer.readUint8();
if (value & 0x80 != 0) {
if (value < 0xe0) {
value = (value & 0x1f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 1;
} else if (value < 0xf0) {
value = (value & 0x0f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 2;
} else {
value = (value & 0x0f) << 18 |
(_buffer.readUint8() & 0x3f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 3;
}
}
result = abi.encodePacked(result, value);
}
return result;
}
}
// File: witnet-ethereum-bridge/contracts/Witnet.sol
/**
* @title A library for decoding Witnet request results
* @notice The library exposes functions to check the Witnet request success.
* and retrieve Witnet results from CBOR values into solidity types.
*/
library Witnet {
using CBOR for CBOR.Value;
/*
STRUCTS
*/
struct Result {
bool success;
CBOR.Value cborValue;
}
/*
ENUMS
*/
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid RADON script.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
Size
}
/*
Result impl's
*/
/**
* @notice Decode raw CBOR bytes into a Result instance.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `Result` instance.
*/
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) {
CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes);
return resultFromCborValue(cborValue);
}
/**
* @notice Decode a CBOR value into a Result instance.
* @param _cborValue An instance of `CBOR.Value`.
* @return A `Result` instance.
*/
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
// Witnet uses CBOR tag 39 to represent RADON error code identifiers.
// [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
/**
* @notice Tell if a Result is successful.
* @param _result An instance of Result.
* @return `true` if successful, `false` if errored.
*/
function isOk(Result memory _result) public pure returns(bool) {
return _result.success;
}
/**
* @notice Tell if a Result is errored.
* @param _result An instance of Result.
* @return `true` if errored, `false` if successful.
*/
function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
/**
* @notice Decode a bytes value from a Result as a `bytes` value.
* @param _result An instance of Result.
* @return The `bytes` decoded from the Result.
*/
function asBytes(Result memory _result) public pure returns(bytes memory) {
require(_result.success, "Tried to read bytes value from errored Result");
return _result.cborValue.decodeBytes();
}
/**
* @notice Decode an error code from a Result as a member of `ErrorCodes`.
* @param _result An instance of `Result`.
* @return The `CBORValue.Error memory` decoded from the Result.
*/
function asErrorCode(Result memory _result) public pure returns(ErrorCodes) {
uint64[] memory error = asRawError(_result);
return supportedErrorOrElseUnknown(error[0]);
}
/**
* @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments.
* @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
* @param _result An instance of `Result`.
* @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message.
*/
function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) {
uint64[] memory error = asRawError(_result);
ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]);
bytes memory errorMessage;
if (errorCode == ErrorCodes.SourceScriptNotCBOR) {
errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value");
} else if (errorCode == ErrorCodes.SourceScriptNotArray) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls");
} else if (errorCode == ErrorCodes.SourceScriptNotRADON) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script");
} else if (errorCode == ErrorCodes.RequestTooManySources) {
errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")");
} else if (errorCode == ErrorCodes.ScriptTooManyCalls) {
errorMessage = abi.encodePacked(
"Script #",
utoa(error[2]),
" from the ",
stageName(error[1]),
" stage contained too many calls (",
utoa(error[3]),
")"
);
} else if (errorCode == ErrorCodes.UnsupportedOperator) {
errorMessage = abi.encodePacked(
"Operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage is not supported"
);
} else if (errorCode == ErrorCodes.HTTP) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved. Failed with HTTP error code: ",
utoa(error[2] / 100),
utoa(error[2] % 100 / 10),
utoa(error[2] % 10)
);
} else if (errorCode == ErrorCodes.RetrievalTimeout) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved because of a timeout."
);
} else if (errorCode == ErrorCodes.Underflow) {
errorMessage = abi.encodePacked(
"Underflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.Overflow) {
errorMessage = abi.encodePacked(
"Overflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.DivisionByZero) {
errorMessage = abi.encodePacked(
"Division by zero at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else {
errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")");
}
return (errorCode, string(errorMessage));
}
/**
* @notice Decode a raw error from a `Result` as a `uint64[]`.
* @param _result An instance of `Result`.
* @return The `uint64[]` raw error as decoded from the `Result`.
*/
function asRawError(Result memory _result) public pure returns(uint64[] memory) {
require(!_result.success, "Tried to read error code from successful Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asFixed16(Result memory _result) public pure returns(int32) {
require(_result.success, "Tried to read `fixed16` value from errored Result");
return _result.cborValue.decodeFixed16();
}
/**
* @notice Decode an array of fixed16 values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asFixed16Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `fixed16[]` value from errored Result");
return _result.cborValue.decodeFixed16Array();
}
/**
* @notice Decode a integer numeric value from a Result as an `int128` value.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
/**
* @notice Decode an array of integer numeric values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asInt128Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `int128[]` value from errored Result");
return _result.cborValue.decodeInt128Array();
}
/**
* @notice Decode a string value from a Result as a `string` value.
* @param _result An instance of Result.
* @return The `string` decoded from the Result.
*/
function asString(Result memory _result) public pure returns(string memory) {
require(_result.success, "Tried to read `string` value from errored Result");
return _result.cborValue.decodeString();
}
/**
* @notice Decode an array of string values from a Result as a `string[]` value.
* @param _result An instance of Result.
* @return The `string[]` decoded from the Result.
*/
function asStringArray(Result memory _result) public pure returns(string[] memory) {
require(_result.success, "Tried to read `string[]` value from errored Result");
return _result.cborValue.decodeStringArray();
}
/**
* @notice Decode a natural numeric value from a Result as a `uint64` value.
* @param _result An instance of Result.
* @return The `uint64` decoded from the Result.
*/
function asUint64(Result memory _result) public pure returns(uint64) {
require(_result.success, "Tried to read `uint64` value from errored Result");
return _result.cborValue.decodeUint64();
}
/**
* @notice Decode an array of natural numeric values from a Result as a `uint64[]` value.
* @param _result An instance of Result.
* @return The `uint64[]` decoded from the Result.
*/
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) {
require(_result.success, "Tried to read `uint64[]` value from errored Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Convert a stage index number into the name of the matching Witnet request stage.
* @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages.
* @return The name of the matching stage.
*/
function stageName(uint64 _stageIndex) public pure returns(string memory) {
if (_stageIndex == 0) {
return "retrieval";
} else if (_stageIndex == 1) {
return "aggregation";
} else if (_stageIndex == 2) {
return "tally";
} else {
return "unknown";
}
}
/**
* @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't
* exist.
* @param _discriminant The numeric identifier of an error.
* @return A member of `ErrorCodes`.
*/
function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) {
if (_discriminant < uint8(ErrorCodes.Size)) {
return ErrorCodes(_discriminant);
} else {
return ErrorCodes.Unknown;
}
}
/**
* @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its.
* three less significant decimal values.
* @param _u A `uint64` value.
* @return The `string` representing its decimal value.
*/
function utoa(uint64 _u) private pure returns(string memory) {
if (_u < 10) {
bytes memory b1 = new bytes(1);
b1[0] = byte(uint8(_u) + 48);
return string(b1);
} else if (_u < 100) {
bytes memory b2 = new bytes(2);
b2[0] = byte(uint8(_u / 10) + 48);
b2[1] = byte(uint8(_u % 10) + 48);
return string(b2);
} else {
bytes memory b3 = new bytes(3);
b3[0] = byte(uint8(_u / 100) + 48);
b3[1] = byte(uint8(_u % 100 / 10) + 48);
b3[2] = byte(uint8(_u % 10) + 48);
return string(b3);
}
}
/**
* @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values.
* @param _u A `uint64` value.
* @return The `string` representing its hexadecimal value.
*/
function utohex(uint64 _u) private pure returns(string memory) {
bytes memory b2 = new bytes(2);
uint8 d0 = uint8(_u / 16) + 48;
uint8 d1 = uint8(_u % 16) + 48;
if (d0 > 57)
d0 += 7;
if (d1 > 57)
d1 += 7;
b2[0] = byte(d0);
b2[1] = byte(d1);
return string(b2);
}
}
// File: witnet-ethereum-bridge/contracts/Request.sol
/**
* @title The serialized form of a Witnet data request
*/
contract Request {
bytes public bytecode;
uint256 public id;
/**
* @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized
* using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using
* the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests.
* The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a
* mismatch and a data request could be resolved with the result of another.
* @param _bytecode Witnet request in bytes.
*/
constructor(bytes memory _bytecode) public {
bytecode = _bytecode;
id = uint256(sha256(_bytecode));
}
}
// File: witnet-ethereum-bridge/contracts/UsingWitnet.sol
/**
* @title The UsingWitnet contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Witnet network.
*/
contract UsingWitnet {
using Witnet for Witnet.Result;
WitnetRequestsBoardProxy internal wrb;
/**
* @notice Include an address to specify the WitnetRequestsBoard.
* @param _wrb WitnetRequestsBoard address.
*/
constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
// contract until a particular request has been successfully accepted into Witnet
modifier witnetRequestAccepted(uint256 _id) {
require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network");
_;
}
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward) {
require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows");
require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards");
_;
}
/**
* @notice Send a new request to the Witnet network
* @dev Call to `post_dr` function in the WitnetRequestsBoard contract
* @param _request An instance of the `Request` contract
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which posts back the request result
* @return Sequencial identifier for the request included in the WitnetRequestsBoard
*/
function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
returns (uint256)
{
return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward);
}
/**
* @notice Check if a request has been accepted into Witnet.
* @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
* parties) before this method returns `true`.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though.
*/
function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) {
// Find the request in the
uint256 drHash = wrb.readDrHash(_id);
// If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the
// request has been proven to the WRB.
return drHash != 0;
}
/**
* @notice Upgrade the rewards for a Data Request previously included.
* @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which post the Data Request result.
*/
function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
{
wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward);
}
/**
* @notice Read the result of a resolved request.
* @dev Call to `read_result` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that was posted to Witnet.
* @return The result of the request as an instance of `Result`.
*/
function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) {
return Witnet.resultFromCborBytes(wrb.readResult(_id));
}
}
// File: adomedianizer/contracts/IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol
// The bytecode of the BitcoinPrice request that will be sent to Witnet
contract BitcoinPriceRequest is Request {
constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the BitcoinPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract BtcUsdPriceFeed is UsingWitnet, IERC2362 {
// The public Bitcoin price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is `keccak256("Price-BTC/USD-3")`
bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new BitcoinPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != BTCUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol
// The bytecode of the EthPrice request that will be sent to Witnet
contract EthPriceRequest is Request {
constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the ethPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract EthUsdPriceFeed is UsingWitnet, IERC2362 {
// The public eth price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")`
bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new EthPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != ETHUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol
// The bytecode of the GoldPrice request that will be sent to Witnet
contract GoldPriceRequest is Request {
constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the goldPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract GoldEurPriceFeed is UsingWitnet, IERC2362 {
// The public gold price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")`
bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new GoldPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != XAUEUR3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: contracts/Deployer.sol
// Import witnet-ethereum-block-relay-contracts
// Import the UsingWitnet library that enables interacting with Witnet
// Import price feeds
contract Deployer {
}
// File: contracts/Migrations.sol
contract Migrations {
address public owner;
uint public lastCompletedMigration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner)
_;
}
function setCompleted(uint _completed) public restricted {
lastCompletedMigration = _completed;
}
function upgrade(address _newAddress) public restricted {
Migrations upgraded = Migrations(_newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| * @notice Include an address to specify the WitnetRequestsBoard. @param _wrb WitnetRequestsBoard address./ | constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
| 901,292 | [
1,
8752,
392,
1758,
358,
4800,
326,
678,
305,
2758,
6421,
22233,
18,
225,
389,
91,
6731,
678,
305,
2758,
6421,
22233,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
12,
2867,
389,
91,
6731,
13,
1071,
288,
203,
565,
341,
6731,
273,
678,
305,
2758,
6421,
22233,
3886,
24899,
91,
6731,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
* @title KosiumPioneer
* KosiumPioneer - a contract for my non-fungible creatures.
*/
contract KosiumPioneer is ERC721, Ownable {
using SafeMath for uint256;
string public baseURI;
bool public saleIsActive = false;
bool public presaleIsActive = false;
uint256 public maxPioneerPurchase = 5;
uint256 public maxPioneerPurchasePresale = 2;
uint256 public constant pioneerPrice = 0.06 ether;
uint256 public MAX_PIONEERS;
uint256 public MAX_PRESALE_PIONEERS = 2000;
uint256 public PIONEERS_RESERVED = 1000;
uint256 public numReserved = 0;
uint256 public numMinted = 0;
mapping(address => bool) public whitelistedPresaleAddresses;
mapping(address => uint256) public presaleBoughtCounts;
constructor(
uint256 maxNftSupply
)
ERC721("Kosium Pioneer", "KPR")
{
MAX_PIONEERS = maxNftSupply;
}
modifier userOnly{
require(tx.origin==msg.sender,"Only a user may call this function");
_;
}
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/**
* Returns base uri for token metadata. Called in ERC721 tokenURI(tokenId)
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* Changes URI used to get token metadata
*/
function setBaseTokenURI(string memory newBaseURI) public onlyOwner {
baseURI = newBaseURI;
}
/**
* Mints numToMint tokens to an address
*/
function mintTo(address _to, uint numToMint) internal {
require(numMinted + numToMint <= MAX_PIONEERS, "Reserving would exceed max number of Pioneers to reserve");
for (uint i = 0; i < numToMint; i++) {
_safeMint(_to, numMinted);
++numMinted;
}
}
/**
* Set some Kosium Pioneers aside
*/
function reservePioneers(address _to, uint numberToReserve) external onlyOwner {
require(numReserved + numberToReserve <= PIONEERS_RESERVED, "Reserving would exceed max number of Pioneers to reserve");
mintTo(_to, numberToReserve);
numReserved += numberToReserve;
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
/*
* Pause presale if active, make active if paused
*/
function flipPresaleState() external onlyOwner {
presaleIsActive = !presaleIsActive;
}
/**
* Mints Kosium Pioneers that have already been bought through pledge
*/
function mintPioneer(uint numberOfTokens) external payable userOnly {
require(saleIsActive, "Sale must be active to mint Pioneer");
require(numberOfTokens <= maxPioneerPurchase, "Can't mint that many tokens at a time");
require(numMinted + numberOfTokens <= MAX_PIONEERS - PIONEERS_RESERVED + numReserved, "Purchase would exceed max supply of Pioneers");
require(pioneerPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
mintTo(msg.sender, numberOfTokens);
}
/**
* Mints Kosium Pioneers for presale
*/
function mintPresalePioneer(uint numberOfTokens) external payable userOnly {
require(presaleIsActive, "Presale must be active to mint Pioneer");
require(whitelistedPresaleAddresses[msg.sender], "Sender address must be whitelisted for presale minting");
require(numberOfTokens + presaleBoughtCounts[msg.sender] <= maxPioneerPurchasePresale, "This whitelisted address cannot mint this many Pioneers in the presale.");
uint newSupplyTotal = numMinted + numberOfTokens;
require(newSupplyTotal <= MAX_PRESALE_PIONEERS + numReserved, "Purchase would exceed max supply of Presale Pioneers");
require(newSupplyTotal <= MAX_PIONEERS - PIONEERS_RESERVED + numReserved, "Purchase would exceed max supply of Pioneers");
require(pioneerPrice.mul(numberOfTokens) <= msg.value, "Provided ETH is below the required price");
mintTo(msg.sender, numberOfTokens);
presaleBoughtCounts[msg.sender] += numberOfTokens;
}
/*
* Add users to the whitelist for the presale
*/
function whitelistAddressForPresale(address[] calldata earlyAdopterAddresses) external onlyOwner{
for (uint i = 0; i < earlyAdopterAddresses.length; i++){
whitelistedPresaleAddresses[earlyAdopterAddresses[i]] = true;
}
}
/*
* Remove users from the whitelist for the presale
*/
function removeFromWhitelist(address[] calldata earlyAdopterAddresses) external onlyOwner{
for (uint i = 0; i < earlyAdopterAddresses.length; i++){
whitelistedPresaleAddresses[earlyAdopterAddresses[i]] = false;
}
}
/*
* Change the max presale limit
*/
function setPresaleLimit(uint maxToPresale) public onlyOwner{
require(maxToPresale <= MAX_PIONEERS, "Presale limit cannot be greater than the max supply of Pioneers.");
MAX_PRESALE_PIONEERS = maxToPresale;
}
/*
* Change the reserved number of Pioneers
*/
function setReserveLimit(uint reservedLimit) public onlyOwner{
require(reservedLimit <= MAX_PIONEERS, "Reserve supply cannot be greater than the max supply of Pioneers.");
require(numReserved <= reservedLimit, "Reserve supply cannot be less than the number of Pioneers already reserved.");
require(reservedLimit < PIONEERS_RESERVED, "Can only reduce the number of Pioneers reserved.");
PIONEERS_RESERVED = reservedLimit;
}
/*
* Change the max number of pioneers each account can purchase at a time in the open sale
*/
function setPurchaseLimit(uint purchaseLimit) public onlyOwner{
require(purchaseLimit <= MAX_PIONEERS, "The max number of pioneers to purchase for each account cannot be greater than the maximum number of Pioneers.");
maxPioneerPurchase = purchaseLimit;
}
/*
* Change the max number of pioneers each account can purchase at a time in the presale
*/
function setPurchaseLimitPresale(uint purchaseLimit) public onlyOwner{
require(purchaseLimit <= MAX_PIONEERS, "The max number of pioneers to purchase for each account cannot be greater than the maximum number of Pioneers.");
maxPioneerPurchasePresale = purchaseLimit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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);
}
} | Remove users from the whitelist for the presale/ | function removeFromWhitelist(address[] calldata earlyAdopterAddresses) external onlyOwner{
for (uint i = 0; i < earlyAdopterAddresses.length; i++){
whitelistedPresaleAddresses[earlyAdopterAddresses[i]] = false;
}
}
| 11,806,565 | [
1,
3288,
3677,
628,
326,
10734,
364,
326,
4075,
5349,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22386,
18927,
12,
2867,
8526,
745,
892,
11646,
1871,
3838,
264,
7148,
13,
3903,
1338,
5541,
95,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
11646,
1871,
3838,
264,
7148,
18,
2469,
31,
277,
27245,
95,
203,
5411,
26944,
12236,
5349,
7148,
63,
2091,
715,
1871,
3838,
264,
7148,
63,
77,
13563,
273,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xeE4Dc4275aD19b0Ef692aA12cf5F1C54DFE0a214/sources/TropicalOtters.sol | turtleId => claim info
| mapping(uint256 => uint256) private claimInfo; | 8,410,766 | [
1,
25271,
5929,
548,
516,
7516,
1123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
3238,
7516,
966,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "./IAccumulator.sol";
import "../libraries/AccumulationLibrary.sol";
import "../libraries/ObservationLibrary.sol";
/**
* @title IPriceAccumulator
* @notice An interface that defines a "price accumulator" - that is, a cumulative price - with a single quote token
* and many exchange tokens.
* @dev Price accumulators are used to calculate time-weighted average prices.
*/
abstract contract IPriceAccumulator is IAccumulator {
/// @notice Emitted when the accumulator is updated.
/// @dev The accumulator's observation and cumulative values are updated when this is emitted.
/// @param token The address of the token that the update is for.
/// @param price The quote token denominated price for a whole token.
/// @param timestamp The epoch timestamp of the update (in seconds).
event Updated(address indexed token, uint256 price, uint256 timestamp);
/**
* @notice Calculates a price from two different cumulative prices.
* @param firstAccumulation The first cumulative price.
* @param secondAccumulation The last cumulative price.
* @dev Reverts if the timestamp of the first accumulation is 0, or if it's not strictly less than the timestamp of
* the second.
* @return price A time-weighted average price derived from two cumulative prices.
*/
function calculatePrice(
AccumulationLibrary.PriceAccumulator calldata firstAccumulation,
AccumulationLibrary.PriceAccumulator calldata secondAccumulation
) external pure virtual returns (uint112 price);
/// @notice Gets the last cumulative price that was stored.
/// @param token The address of the token to get the cumulative price for.
/// @return The last cumulative price along with the timestamp of that price.
function getLastAccumulation(address token)
public
view
virtual
returns (AccumulationLibrary.PriceAccumulator memory);
/// @notice Gets the current cumulative price.
/// @param token The address of the token to get the cumulative price for.
/// @return The current cumulative price along with the timestamp of that price.
function getCurrentAccumulation(address token)
public
view
virtual
returns (AccumulationLibrary.PriceAccumulator memory);
}
| * @title IPriceAccumulator @notice An interface that defines a "price accumulator" - that is, a cumulative price - with a single quote token and many exchange tokens. @dev Price accumulators are used to calculate time-weighted average prices./ | abstract contract IPriceAccumulator is IAccumulator {
event Updated(address indexed token, uint256 price, uint256 timestamp);
function calculatePrice(
AccumulationLibrary.PriceAccumulator calldata firstAccumulation,
AccumulationLibrary.PriceAccumulator calldata secondAccumulation
) external pure virtual returns (uint112 price);
function getLastAccumulation(address token)
public
view
virtual
returns (AccumulationLibrary.PriceAccumulator memory);
function getCurrentAccumulation(address token)
public
view
virtual
returns (AccumulationLibrary.PriceAccumulator memory);
pragma solidity >=0.5.0 <0.9.0;
}
| 12,955,945 | [
1,
2579,
3057,
27361,
225,
1922,
1560,
716,
11164,
279,
315,
8694,
13514,
6,
300,
716,
353,
16,
279,
15582,
6205,
300,
598,
279,
2202,
3862,
1147,
282,
471,
4906,
7829,
2430,
18,
225,
20137,
8822,
3062,
854,
1399,
358,
4604,
813,
17,
30890,
8164,
19827,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
2971,
3057,
27361,
353,
467,
27361,
288,
203,
565,
871,
19301,
12,
2867,
8808,
1147,
16,
2254,
5034,
6205,
16,
2254,
5034,
2858,
1769,
203,
203,
565,
445,
4604,
5147,
12,
203,
3639,
15980,
5283,
367,
9313,
18,
5147,
27361,
745,
892,
1122,
8973,
5283,
367,
16,
203,
3639,
15980,
5283,
367,
9313,
18,
5147,
27361,
745,
892,
2205,
8973,
5283,
367,
203,
565,
262,
3903,
16618,
5024,
1135,
261,
11890,
17666,
6205,
1769,
203,
203,
565,
445,
7595,
8973,
5283,
367,
12,
2867,
1147,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
8973,
5283,
367,
9313,
18,
5147,
27361,
3778,
1769,
203,
203,
565,
445,
5175,
8973,
5283,
367,
12,
2867,
1147,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
8973,
5283,
367,
9313,
18,
5147,
27361,
3778,
1769,
203,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x0516a0C508B15F4CB8ea349128ea671987e785D3/sources/final.sol | * THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY. PLEASE DO NOT USE THIS CODE IN PRODUCTION./ | contract RandomNumberConsumer is VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
mapping (uint => uint) public random;
uint256 public randomResult;
uint[] public shuffle;
constructor()
VRFConsumerBase(
) public
{
keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;
}
function getRandomNumber() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(keyHash, fee);
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = randomness;
}
function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues,uint256[] memory cards) {
expandedValues = new uint256[](n);
cards = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
cards[i]=i;
}
return (expandedValues,cards);
}
function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues,uint256[] memory cards) {
expandedValues = new uint256[](n);
cards = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
cards[i]=i;
}
return (expandedValues,cards);
}
function quickSort(uint[] memory arr, int left, int right) pure internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
function quickSort(uint[] memory arr, int left, int right) pure internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
function quickSort(uint[] memory arr, int left, int right) pure internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
function sort(uint[] memory data) public pure returns (uint[] memory) {
quickSort(data, int(0), int(data.length - 1));
return data;
}
function dataSetter(uint256 randomValue, uint256 n) public returns(uint[] memory){
uint[] memory cards = new uint256[](n);
uint[] memory expandedValues = new uint256[](n);
uint[] memory shuffled = new uint256[](n);
uint[] memory sortedExpandedValues = new uint256[](n);
(expandedValues,cards)=expand(randomValue,n);
for ( uint256 i = 0; i <= n-1; i++) {
random[expandedValues[i]]=cards[i];
}
sortedExpandedValues = sort(expandedValues);
for( uint256 j = 0; j <= n-1; j++) {
shuffled[j] = random[sortedExpandedValues[j]];
}
shuffle=shuffled;
return shuffled;
}
function dataSetter(uint256 randomValue, uint256 n) public returns(uint[] memory){
uint[] memory cards = new uint256[](n);
uint[] memory expandedValues = new uint256[](n);
uint[] memory shuffled = new uint256[](n);
uint[] memory sortedExpandedValues = new uint256[](n);
(expandedValues,cards)=expand(randomValue,n);
for ( uint256 i = 0; i <= n-1; i++) {
random[expandedValues[i]]=cards[i];
}
sortedExpandedValues = sort(expandedValues);
for( uint256 j = 0; j <= n-1; j++) {
shuffled[j] = random[sortedExpandedValues[j]];
}
shuffle=shuffled;
return shuffled;
}
function dataSetter(uint256 randomValue, uint256 n) public returns(uint[] memory){
uint[] memory cards = new uint256[](n);
uint[] memory expandedValues = new uint256[](n);
uint[] memory shuffled = new uint256[](n);
uint[] memory sortedExpandedValues = new uint256[](n);
(expandedValues,cards)=expand(randomValue,n);
for ( uint256 i = 0; i <= n-1; i++) {
random[expandedValues[i]]=cards[i];
}
sortedExpandedValues = sort(expandedValues);
for( uint256 j = 0; j <= n-1; j++) {
shuffled[j] = random[sortedExpandedValues[j]];
}
shuffle=shuffled;
return shuffled;
}
function shuffleGetter() public view returns(uint[] memory){
return shuffle;
}
function randomGetter(uint256 key) public view returns(uint){
return random[key];
}
} | 5,611,171 | [
1,
2455,
5127,
4437,
8175,
5675,
21373,
8020,
2849,
1268,
14735,
45,
1792,
14988,
55,
670,
985,
5528,
1212,
2056,
13477,
12108,
14934,
985,
4107,
18,
453,
22357,
5467,
4269,
14988,
20676,
11128,
2120,
11770,
1212,
27035,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8072,
1854,
5869,
353,
776,
12918,
5869,
2171,
288,
203,
377,
203,
565,
1731,
1578,
2713,
498,
2310,
31,
203,
565,
2254,
5034,
2713,
14036,
31,
203,
565,
2874,
261,
11890,
516,
2254,
13,
1071,
2744,
31,
203,
203,
377,
203,
565,
2254,
5034,
1071,
2744,
1253,
31,
203,
565,
2254,
8526,
1071,
12552,
31,
203,
565,
3885,
1435,
7010,
3639,
776,
12918,
5869,
2171,
12,
203,
3639,
262,
1071,
203,
565,
288,
203,
3639,
498,
2310,
273,
374,
92,
26,
73,
5877,
70,
4313,
29,
69,
1611,
10241,
4313,
72,
2643,
71,
378,
26,
69,
28,
73,
11212,
73,
6028,
713,
72,
26,
311,
7140,
7414,
5026,
72,
24,
69,
25,
5608,
28,
70,
27,
3462,
72,
7677,
74,
28,
8285,
70,
23,
69,
24,
31,
203,
565,
289,
203,
377,
203,
565,
445,
20581,
1854,
1435,
1071,
1135,
261,
3890,
1578,
14459,
13,
288,
203,
3639,
2583,
12,
10554,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
14036,
16,
315,
1248,
7304,
22926,
300,
3636,
6835,
598,
11087,
5286,
278,
8863,
203,
3639,
327,
590,
8529,
4496,
12,
856,
2310,
16,
14036,
1769,
203,
565,
289,
203,
203,
565,
445,
22290,
8529,
4496,
12,
3890,
1578,
14459,
16,
2254,
5034,
2744,
4496,
13,
2713,
3849,
288,
203,
3639,
2744,
1253,
273,
2744,
4496,
31,
203,
565,
289,
203,
203,
203,
915,
4542,
12,
11890,
5034,
2744,
620,
16,
2254,
5034,
290,
13,
1071,
16618,
1135,
261,
11890,
5034,
8526,
3778,
8406,
1972,
16,
11890,
5034,
8526,
3778,
18122,
13,
288,
2
] |
./full_match/56/0xa3585d3BcDDA3917942a2410e0cE4599b3bD47d4/sources/project:/contracts/rules/interactionRules/InvestorHasNTT.sol | @notice checks if the `_accountsToCheck` pass the conditions of the rule @param _accountsToCheck list of addresses to check @return true if all addresses passed the validation | function checkRule(
address[] memory _accountsToCheck
) external view returns (bool) {
for (uint256 i = 0; i < _accountsToCheck.length; i++) {
_checkIfHasSoulbID(_accountsToCheck[i]);
}
return true;
}
| 3,257,643 | [
1,
12366,
309,
326,
1375,
67,
4631,
11634,
1564,
68,
1342,
326,
4636,
434,
326,
1720,
225,
389,
4631,
11634,
1564,
666,
434,
6138,
358,
866,
327,
638,
309,
777,
6138,
2275,
326,
3379,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
866,
2175,
12,
203,
3639,
1758,
8526,
3778,
389,
4631,
11634,
1564,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
4631,
11634,
1564,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
1893,
2047,
5582,
55,
1003,
70,
734,
24899,
4631,
11634,
1564,
63,
77,
19226,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ERC721AKarine.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
// import "hardhat/console.sol";
contract KarineDAO is ERC721AKarine, Ownable, Pausable, ReentrancyGuard, IERC2981 {
string private _baseTokenURI;
mapping(address => bool) private _proxyRegistryAddress;
uint256[5] private _mosaicDataArr; // 5*256 bit to store 1158 bit location of mosaic nft
// init swapNFTMapping and alter value when random later
uint8[147] private _canNotMintNFTMapping; // use for random swap nft
uint64 private _privateOpenTime;
uint64 private _publicOpenTime;
uint64 private _revelationTime;
uint16 private _startIndex = 0;
uint16 internal _royalty = 680; // base 10000, 6.8%
uint32 internal randNonce = 0;
uint16 private _canMintNFTMinted;
uint16 private _canMintNFTMintedAfterRevelation;
uint8 private _canNotMintNFTMinted;
bool private _revelated = false;
address payable private _productOwnerAddr;
// constant
uint256 public constant VERSION = 10204;
uint16 public constant BASE = 10000; // base for royalty
uint8 public immutable MAX_MINT_TIER_1 = 3;
uint8 public immutable MAX_MINT_TIER_2 = 1;
uint8 public immutable MAX_MINT_PUBLIC = 10;
/// @dev NFT JSON ID map : | 210 premint | 1158 can mint | 147 swap only |
/// @dev NFT ID map : | 210 premint | <= 1158 can mint | 147 swap only ~ can mint left |
uint16 public immutable TOTAL_PREMINT_NFT;
uint16 public immutable TOTAL_CAN_MINT_NFT;
uint16 public immutable TOTAL_CANNOT_MINT_NFT;
uint256 public immutable PRIVATE_PRICE;
uint256 public immutable PUBLIC_PRICE;
constructor(
string memory baseURI,
address payable productOwnerAddr,
uint256[5] memory mosaicDataArr,
uint64 privateOpenTime,
uint64 publicOpenTime,
uint64 revelationTime,
uint16 totalPremintNFT,
uint16 totalCanmintNFT,
uint16 totalCannotmintNFT,
uint256 privatePrice,
uint256 publicPrice
) ERC721AKarine("KarineDAO", "KarineDAO") {
_baseTokenURI = baseURI;
_productOwnerAddr = productOwnerAddr;
_mosaicDataArr = mosaicDataArr;
_privateOpenTime = privateOpenTime;
_publicOpenTime = publicOpenTime;
_revelationTime = revelationTime;
// init immutable
TOTAL_PREMINT_NFT = totalPremintNFT;
TOTAL_CAN_MINT_NFT = totalCanmintNFT;
TOTAL_CANNOT_MINT_NFT = totalCannotmintNFT;
PRIVATE_PRICE = privatePrice;
PUBLIC_PRICE = publicPrice;
// init swapNFTMapping and alter value when random later
for (uint8 i = 0; i < totalCannotmintNFT; i++) {
_canNotMintNFTMapping[i] = i;
}
_safeMint(_productOwnerAddr, totalPremintNFT);
}
///@dev productOwner addr
function setProductOwner(address addr) external onlyOwner {
_productOwnerAddr = payable(addr);
}
function getProductOwner() external view returns (address) {
return _productOwnerAddr;
}
///@dev allow set _mosaicDataArr before _revelated to avoid issue
function setMosaicDataArr(uint256[5] memory mosaicDataArr) external onlyOwner {
require(!_revelated);
_mosaicDataArr = mosaicDataArr;
}
///@dev setTime
function setTime(
uint64 privateOpenTime,
uint64 publicOpenTime,
uint64 revelationTime
) external onlyOwner {
require(!_revelated);
_privateOpenTime = privateOpenTime;
_publicOpenTime = publicOpenTime;
_revelationTime = revelationTime;
}
/**
@dev royalty
*/
function royaltyInfo(uint256, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
return (_productOwnerAddr, (_salePrice * _royalty) / BASE);
}
function setRoyalty(uint16 royalty) external onlyOwner {
_royalty = royalty;
}
///@dev white list
function addToWhiteList1(address[] memory addrArr) external {
require((msg.sender == _productOwnerAddr) || (msg.sender == owner()));
for (uint256 i = 0; i < addrArr.length; i++) {
_addressData[addrArr[i]].limitPrivateMint = MAX_MINT_TIER_1;
}
}
function addToWhiteList2(address[] memory addrArr) external {
require((msg.sender == _productOwnerAddr) || (msg.sender == owner()));
for (uint256 i = 0; i < addrArr.length; i++) {
_addressData[addrArr[i]].limitPrivateMint = MAX_MINT_TIER_2;
}
}
function removeFromWhiteList(address[] memory addrArr) external {
require((msg.sender == _productOwnerAddr) || (msg.sender == owner()));
for (uint256 i = 0; i < addrArr.length; i++) {
_addressData[addrArr[i]].limitPrivateMint = 0;
}
}
function getPrivateLimitOfAddr(address addr) external view returns (uint8) {
return _addressData[addr].limitPrivateMint;
}
///@dev cannot underflow if everything correct
function getMintTimesLeft(address addr, bool isPrivate) external view returns (uint256) {
if (!_revelated) {
if (isPrivate) {
if (_addressData[addr].limitPrivateMint > _addressData[addr].numberPrivateMinted) {
return _addressData[addr].limitPrivateMint - _addressData[addr].numberPrivateMinted;
} else {
return 0;
}
} else {
return MAX_MINT_PUBLIC - (_numberMinted(addr) - _addressData[addr].numberPrivateMinted);
}
} else {
if (addr == _productOwnerAddr) {
return TOTAL_CAN_MINT_NFT - (_canMintNFTMinted + _canMintNFTMintedAfterRevelation);
} else {
return 0;
}
}
}
// check mosaic nft
function isMosaic(uint16 tokenId) public view returns (bool) {
if (!_revelated || tokenId < TOTAL_PREMINT_NFT) {
return false;
}
uint16 indexInCanMintNFT = tokenIdToIndex(tokenId) - TOTAL_PREMINT_NFT;
uint16 idxInMosaicDataArr = indexInCanMintNFT / 256;
if (idxInMosaicDataArr >= _mosaicDataArr.length) {
return false;
}
// get bit info
uint256 bitValue = (_mosaicDataArr[idxInMosaicDataArr] & (1 << (indexInCanMintNFT % 256)));
return bitValue > 0;
}
/// @dev minting
/**
* @dev mints `numToken` tokens and assigns it to
* `msg.sender` by calling _safeMint function.
*
* Requirements:
* - Current timestamp must within period of private sale `_privateOpenTime` - `_publicOpenTime`.
* - Ether amount sent greater or equal the `PRIVATE_PRICE` multipled by `numToken`.
* - `numToken` within limits of max number of tokens minted in single txn.
* @param numToken - Number of tokens to be minted
*/
function mintPrivateSale(uint8 numToken) external payable whenNotPaused {
uint256 time = block.timestamp;
require(
(!_revelated) &&
(time >= _privateOpenTime && time < _publicOpenTime) &&
_addressData[msg.sender].limitPrivateMint > 0,
"Mint is not open"
);
require((_canMintNFTMinted + numToken) <= TOTAL_CAN_MINT_NFT, "Out of stock");
require(!Address.isContract(msg.sender));
require(numToken > 0, "Empty numToken");
require(msg.value >= PRIVATE_PRICE * numToken, "Insufficient ETH");
require(
(_addressData[msg.sender].numberPrivateMinted + numToken) <= _addressData[msg.sender].limitPrivateMint,
"Out of times"
);
_addressData[msg.sender].numberPrivateMinted += numToken;
_canMintNFTMinted += numToken;
_safeMint(msg.sender, numToken);
}
/**
* @dev mints `numToken` tokens and assigns it to
* `msg.sender` by calling _safeMint function.
*
* Requirements:
* - Current timestamp must within period of public sale `_publicOpenTime` - `_revelationTime`.
* - Ether amount sent greater or equal the `PUBLIC_PRICE` multipled by `numToken`.
* - `numToken` within limits of max number of tokens minted in single txn.
* @param numToken - Number of tokens to be minted
*/
function mintPublicSale(uint8 numToken) external payable whenNotPaused {
uint256 time = block.timestamp;
require((!_revelated) && (time >= _publicOpenTime && time < _revelationTime), "Mint is not open");
require((_canMintNFTMinted + numToken) <= TOTAL_CAN_MINT_NFT, "Out of stock");
require(!Address.isContract(msg.sender));
require(numToken > 0, "Empty numToken");
require(msg.value >= PUBLIC_PRICE * numToken, "Insufficient ETH");
require(
(_numberMinted(msg.sender) - _addressData[msg.sender].numberPrivateMinted) + numToken <= MAX_MINT_PUBLIC,
"Out of times"
);
_canMintNFTMinted += numToken;
_safeMint(msg.sender, numToken);
}
function mintAndTransferAfterRevelation(uint16 numToken, address addr) external whenNotPaused {
require(_revelated && msg.sender == _productOwnerAddr);
require((_canMintNFTMinted + _canMintNFTMintedAfterRevelation + numToken) <= TOTAL_CAN_MINT_NFT, "Out of NFT");
uint256 startTokenId = _currentIndex;
for (uint16 i = 0; i < numToken; i++) {
_ownerships[startTokenId].isCanMintNFT = true;
_ownerships[startTokenId].mappingIndex = _canMintNFTMinted + _canMintNFTMintedAfterRevelation + i;
startTokenId++;
}
_canMintNFTMintedAfterRevelation += numToken;
_safeMint(addr, numToken);
}
/**
@dev revelation
*/
function revelate(string memory baseTokenURI, bool mintAllUnMinted) external onlyOwner {
require(block.timestamp >= _revelationTime);
if (mintAllUnMinted) {
_safeMint(_productOwnerAddr, TOTAL_CAN_MINT_NFT - _canMintNFTMinted);
_canMintNFTMinted = TOTAL_CAN_MINT_NFT;
}
// random _startIndex
_startIndex = uint16(random(TOTAL_CAN_MINT_NFT));
_baseTokenURI = baseTokenURI;
_revelated = true;
}
function emergencyUnrevelate() external onlyOwner {
_revelated = false;
}
/**
@dev swap
*/
function random(uint256 _modulus) private returns (uint256) {
randNonce++;
return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % _modulus;
}
function swap(uint16[] memory tokenIds) external whenNotPaused {
require(block.timestamp >= _revelationTime && _revelated, "Swap is not open");
require((tokenIds.length % 2) == 0, "Length must be even");
uint8 numToken = uint8(tokenIds.length / 2);
require((_canNotMintNFTMinted + numToken) <= TOTAL_CANNOT_MINT_NFT, "Out of NFT");
for (uint16 i = 0; i < tokenIds.length; i++) {
require(isMosaic(tokenIds[i]), "Only use mosaic");
}
// transfer all mosaic to product owner address
for (uint16 i = 0; i < tokenIds.length; i++) {
transferFrom(msg.sender, _productOwnerAddr, tokenIds[i]);
}
// random NFT
uint256 startTokenId = _currentIndex;
uint8 updatedCanNotMintNFTMinted = _canNotMintNFTMinted;
for (uint8 i = 0; i < numToken; i++) {
uint8 randomNumber = updatedCanNotMintNFTMinted +
uint8(random(TOTAL_CANNOT_MINT_NFT - updatedCanNotMintNFTMinted));
// swap value in _canNotMintNFTMapping
uint8 temp = _canNotMintNFTMapping[randomNumber];
_canNotMintNFTMapping[randomNumber] = _canNotMintNFTMapping[updatedCanNotMintNFTMinted];
_canNotMintNFTMapping[updatedCanNotMintNFTMinted] = temp;
_ownerships[startTokenId].isCanMintNFT = false;
_ownerships[startTokenId].mappingIndex = temp;
startTokenId++;
updatedCanNotMintNFTMinted++;
}
_canNotMintNFTMinted = updatedCanNotMintNFTMinted;
// mint NFT to msg.sender
_safeMint(msg.sender, numToken);
}
/**
@dev tokenUri
*/
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) external onlyOwner {
require(!_revelated);
_baseTokenURI = baseURI;
}
function tokenIdToIndex(uint256 tokenId) public view returns (uint16) {
if (!_revelated) {
return uint16(tokenId);
}
uint256 index;
if (tokenId < TOTAL_PREMINT_NFT) {
// for premint NFT mint in correct time
index = tokenId + _startIndex;
index %= TOTAL_PREMINT_NFT;
} else if (tokenId < (TOTAL_PREMINT_NFT + _canMintNFTMinted)) {
// for canmint NFT mint in correct time
index = (tokenId - TOTAL_PREMINT_NFT) + _startIndex;
index %= TOTAL_CAN_MINT_NFT;
index += TOTAL_PREMINT_NFT;
} else if (_ownerships[tokenId].isCanMintNFT) {
// for canmint NFT mint after revelation
index = _ownerships[tokenId].mappingIndex + _startIndex;
index %= TOTAL_CAN_MINT_NFT;
index += TOTAL_PREMINT_NFT;
} else {
// for can not mint nft
index = _ownerships[tokenId].mappingIndex + TOTAL_PREMINT_NFT + TOTAL_CAN_MINT_NFT;
}
return uint16(index);
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
uint256 index = tokenIdToIndex(tokenId);
return
bytes(baseURI).length != 0
? string(abi.encodePacked(baseURI, Strings.toString(index), ".json"))
: string(abi.encodePacked(Strings.toString(index), ".json"));
}
/**
@dev withdraw
*/
function withdraw() external nonReentrant whenNotPaused {
require(msg.sender == _productOwnerAddr);
payable(msg.sender).transfer(address(this).balance);
}
/** @dev pause */
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
/**
@dev get tokenId to nft mapping
*/
function getAllTokenIdToIndex() external view returns (uint16[] memory) {
uint16[] memory allTokenIdToIndex = new uint16[](_currentIndex);
for (uint256 i; i < _currentIndex; i++) {
allTokenIdToIndex[i] = uint16(tokenIdToIndex(i));
}
return allTokenIdToIndex;
}
function getPrivateOpenTime() external view returns (uint64) {
return _privateOpenTime;
}
function getPublicOpenTime() external view returns (uint64) {
return _publicOpenTime;
}
function getRevelationTime() external view returns (uint64) {
return _revelationTime;
}
function getStartIndex() external view returns (uint16) {
return _startIndex;
}
function getCanMintNFTMinted() external view returns (uint16) {
return _canMintNFTMinted + _canMintNFTMintedAfterRevelation;
}
function getCanNotMintNFTMinted() external view returns (uint16) {
return _canNotMintNFTMinted;
}
function getMosaicDataArr() external view returns (uint256[5] memory) {
return _mosaicDataArr;
}
function getRevelated() external view returns (bool) {
return _revelated;
}
/**
* Override isApprovedForAll to whitelisted marketplaces to enable gas-free listings.
*
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// check if this is an approved marketplace
if (_proxyRegistryAddress[operator]) {
return true;
}
// otherwise, use the default ERC721 isApprovedForAll()
return super.isApprovedForAll(owner, operator);
}
/*
* Function to set status of proxy contracts addresses
*
*/
function setProxy(address proxyAddress, bool value) external onlyOwner {
_proxyRegistryAddress[proxyAddress] = value;
}
}
// 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
// Creator: Chiru Labs
// Custom: Tokenize NFT Team
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
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 and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes 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**128 - 1 (max value of uint128).
*/
contract ERC721AKarine is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
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;
// Use for custom TokenURI
bool isCanMintNFT;
uint16 mappingIndex;
}
// 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 private mint
uint8 numberPrivateMinted;
uint8 limitPrivateMint;
}
// Compiler will pack the following
// _currentIndex and _burnCounter into a single 256bit word.
// The tokenId of the next token to be minted.
uint128 internal _currentIndex;
// The number of tokens burned.
uint128 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) internal _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) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
* 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 tokenByIndex(uint256 index) public view override returns (uint256) {
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
// 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.burned) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert TokenIndexOutOfBounds();
}
/**
* @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) {
if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
uint256 numMintedSoFar = _currentIndex;
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.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
// Execution should never reach this point.
revert();
}
/**
* @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) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* 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 (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 = ERC721AKarine.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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1
// updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = uint128(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**128.
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**128.
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 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 TransferToNonERC721ReceiverImplementer();
} 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.
* 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect 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);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 {}
/**
* @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.
* - `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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (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);
/**
* @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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol"; | * @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 && !_ownerships[tokenId].burned;
}
| 1,296,025 | [
1,
1356,
2856,
1375,
2316,
548,
68,
1704,
18,
13899,
848,
506,
7016,
635,
3675,
3410,
578,
20412,
9484,
3970,
288,
12908,
537,
97,
578,
288,
542,
23461,
1290,
1595,
5496,
13899,
787,
2062,
1347,
2898,
854,
312,
474,
329,
21863,
67,
81,
474,
68,
3631,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
1808,
12,
11890,
5034,
1147,
548,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
1147,
548,
411,
389,
2972,
1016,
597,
401,
67,
995,
12565,
87,
63,
2316,
548,
8009,
70,
321,
329,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xafB8D3F0d92461d3c860E4F7FA1B28a5BF8a1cF8/sources/MintingNFT.sol | Returns current counts of NFTs that have been already minted */ | function myTotalSupply() public view returns(uint[] memory res){
return currentCounts;
}
| 874,111 | [
1,
1356,
783,
6880,
434,
423,
4464,
87,
716,
1240,
2118,
1818,
312,
474,
329,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3399,
5269,
3088,
1283,
1435,
1071,
1476,
1135,
12,
11890,
8526,
3778,
400,
15329,
203,
3639,
327,
783,
9211,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @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;
}
}
contract NodeList is Ownable {
event NodeListed(address publicKey, uint256 epoch, uint256 position);
struct Details {
string declaredIp;
uint256 position;
uint256 pubKx;
uint256 pubKy;
string nodePort;
}
mapping (uint256 => mapping (address => bool)) whitelist;
mapping (address => mapping (uint256 => Details)) public addressToNodeDetailsLog; //mapping of address => epoch => nodeDetailsLog
mapping (uint256 => address[]) public nodeList; // mapping of epoch => list of nodes in epoch
uint256 latestEpoch = 0; //count of number of epochs
constructor() public {
}
//views nodes in the epoch, now requires specified epochs
function viewNodes(uint256 epoch) external view returns (address[], uint256[]) {
uint256[] memory positions = new uint256[](nodeList[epoch].length);
for (uint256 i = 0; i < nodeList[epoch].length; i++) {
positions[i] = addressToNodeDetailsLog[nodeList[epoch][i]][epoch].position;
}
return (nodeList[epoch], positions);
}
function viewNodeListCount(uint256 epoch) external view returns (uint256) {
return nodeList[epoch].length;
}
function viewLatestEpoch() external view returns (uint256) {
return latestEpoch;
}
function viewNodeDetails(uint256 epoch, address node) external view returns (string declaredIp, uint256 position, string nodePort) {
declaredIp = addressToNodeDetailsLog[node][epoch].declaredIp;
position = addressToNodeDetailsLog[node][epoch].position;
nodePort = addressToNodeDetailsLog[node][epoch].nodePort;
}
function viewWhitelist(uint256 epoch, address nodeAddress) public view returns (bool) {
return whitelist[epoch][nodeAddress];
}
modifier whitelisted(uint256 epoch) {
require(whitelist[epoch][msg.sender]);
_;
}
function updateWhitelist(uint256 epoch, address nodeAddress, bool allowed) public onlyOwner {
whitelist[epoch][nodeAddress] = allowed;
}
function listNode(uint256 epoch, string declaredIp, uint256 pubKx, uint256 pubKy, string nodePort) external whitelisted(epoch) {
nodeList[epoch].push(msg.sender);
addressToNodeDetailsLog[msg.sender][epoch] = Details({
declaredIp: declaredIp,
position: nodeList[epoch].length, //so that Position (or node index) starts from 1
pubKx: pubKx,
pubKy: pubKy,
nodePort: nodePort
});
//for now latest epoch is simply the highest epoch registered TODO: only we should be able to call this function
if (latestEpoch < epoch) {
latestEpoch = epoch;
}
emit NodeListed(msg.sender, epoch, nodeList[epoch].length);
}
} | count of number of epochs
| uint256 latestEpoch = 0; | 14,033,247 | [
1,
1883,
434,
1300,
434,
25480,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
4891,
14638,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.10;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface TRC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {TRC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {TRC20-approve}.
*/
contract ERC20 is Context, TRC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// allocating 30 million tokens for promotion, airdrop, liquidity and dev share
uint256 private _totalSupply = 30000000 * (10 ** 8);
constructor() public {
_balances[msg.sender] = _totalSupply;
}
/**
* @dev See {TRC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {TRC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {TRC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {TRC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {TRC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {TRC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {TRC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {TRC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev External function to destroys `amount` tokens from `account`, reducing the
* total supply.
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract GlobalsAndUtility is ERC20 {
/* XfLobbyEnter
*/
event XfLobbyEnter(
uint256 timestamp,
uint256 enterDay,
uint256 indexed entryIndex,
uint256 indexed rawAmount
);
/* XfLobbyExit
*/
event XfLobbyExit(
uint256 timestamp,
uint256 enterDay,
uint256 indexed entryIndex,
uint256 indexed xfAmount,
address indexed referrerAddr
);
/* DailyDataUpdate
*/
event DailyDataUpdate(
address indexed updaterAddr,
uint256 timestamp,
uint256 beginDay,
uint256 endDay
);
/* StakeStart
*/
event StakeStart(
uint40 indexed stakeId,
address indexed stakerAddr,
uint256 stakedSuns,
uint256 stakeShares,
uint256 stakedDays
);
/* StakeGoodAccounting
*/
event StakeGoodAccounting(
uint40 indexed stakeId,
address indexed stakerAddr,
address indexed senderAddr,
uint256 stakedSuns,
uint256 stakeShares,
uint256 payout,
uint256 penalty
);
/* StakeEnd
*/
event StakeEnd(
uint40 indexed stakeId,
uint40 prevUnlocked,
address indexed stakerAddr,
uint256 lockedDay,
uint256 servedDays,
uint256 stakedSuns,
uint256 stakeShares,
uint256 dividends,
uint256 payout,
uint256 penalty,
uint256 stakeReturn
);
/* ShareRateChange
*/
event ShareRateChange(
uint40 indexed stakeId,
uint256 timestamp,
uint256 newShareRate
);
/* Flush address */
address payable internal constant FLUSH_ADDR = 0x964216236CAa8F5133aB6A81F2Cb9cA1e8944171;
/* T2X allocation share address */
address payable internal constant T2X_SHARE_ADDR = 0x769902b4cB2dfD79F2370555AD255Bf599bF7155;
uint8 internal LAST_FLUSHED_DAY = 1;
/* ERC20 constants */
string public constant name = "E2X";
string public constant symbol = "E2X";
uint8 public constant decimals = 8;
/* Suns per Satoshi = 10,000 * 1e8 / 1e8 = 1e4 */
uint256 private constant SUNS_PER_E2X = 10 ** uint256(decimals); // 1e8
/* Time of contract launch (2020-7-11T00:00:00Z) */
uint256 internal constant LAUNCH_TIME = 1594425600;
/* Start of claim phase */
uint256 internal constant PRE_CLAIM_DAYS = 1;
uint256 internal constant CLAIM_STARTING_AMOUNT = 5000000 * (10 ** 8);
uint256 internal constant CLAIM_LOWEST_AMOUNT = 1000000 * (10 ** 8);
uint256 internal constant CLAIM_PHASE_START_DAY = PRE_CLAIM_DAYS;
/* Number of words to hold 1 bit for each transform lobby day */
uint256 internal constant XF_LOBBY_DAY_WORDS = ((1 + (50 * 7)) + 255) >> 8;
/* Stake timing parameters */
uint256 internal constant MIN_STAKE_DAYS = 1;
uint256 internal constant MAX_STAKE_DAYS = 5555; // Approx 15 years
uint256 internal constant EARLY_PENALTY_MIN_DAYS = 90;
uint256 private constant LATE_PENALTY_GRACE_WEEKS = 2;
uint256 internal constant LATE_PENALTY_GRACE_DAYS = LATE_PENALTY_GRACE_WEEKS * 7;
uint256 private constant LATE_PENALTY_SCALE_WEEKS = 100;
uint256 internal constant LATE_PENALTY_SCALE_DAYS = LATE_PENALTY_SCALE_WEEKS * 7;
/* Stake shares Longer Pays Better bonus constants used by _stakeStartBonusSuns() */
uint256 private constant LPB_BONUS_PERCENT = 20;
uint256 private constant LPB_BONUS_MAX_PERCENT = 200;
uint256 internal constant LPB = 364 * 100 / LPB_BONUS_PERCENT;
uint256 internal constant LPB_MAX_DAYS = LPB * LPB_BONUS_MAX_PERCENT / 100;
/* Stake shares Bigger Pays Better bonus constants used by _stakeStartBonusSuns() */
uint256 private constant BPB_BONUS_PERCENT = 10;
uint256 private constant BPB_MAX_E2X = 7 * 1e6;
uint256 internal constant BPB_MAX_SUNS = BPB_MAX_E2X * SUNS_PER_E2X;
uint256 internal constant BPB = BPB_MAX_SUNS * 100 / BPB_BONUS_PERCENT;
/* Share rate is scaled to increase precision */
uint256 internal constant SHARE_RATE_SCALE = 1e5;
/* Share rate max (after scaling) */
uint256 internal constant SHARE_RATE_UINT_SIZE = 40;
uint256 internal constant SHARE_RATE_MAX = (1 << SHARE_RATE_UINT_SIZE) - 1;
/* weekly staking bonus */
uint8 internal constant BONUS_DAY_SCALE = 2;
/* Globals expanded for memory (except _latestStakeId) and compact for storage */
struct GlobalsCache {
uint256 _lockedSunsTotal;
uint256 _nextStakeSharesTotal;
uint256 _shareRate;
uint256 _stakePenaltyTotal;
uint256 _dailyDataCount;
uint256 _stakeSharesTotal;
uint40 _latestStakeId;
uint256 _currentDay;
}
struct GlobalsStore {
uint72 lockedSunsTotal;
uint72 nextStakeSharesTotal;
uint40 shareRate;
uint72 stakePenaltyTotal;
uint16 dailyDataCount;
uint72 stakeSharesTotal;
uint40 latestStakeId;
}
GlobalsStore public globals;
/* Daily data */
struct DailyDataStore {
uint72 dayPayoutTotal;
uint256 dayDividends;
uint72 dayStakeSharesTotal;
}
mapping(uint256 => DailyDataStore) public dailyData;
/* Stake expanded for memory (except _stakeId) and compact for storage */
struct StakeCache {
uint40 _stakeId;
uint256 _stakedSuns;
uint256 _stakeShares;
uint256 _lockedDay;
uint256 _stakedDays;
uint256 _unlockedDay;
}
struct StakeStore {
uint40 stakeId;
uint72 stakedSuns;
uint72 stakeShares;
uint16 lockedDay;
uint16 stakedDays;
uint16 unlockedDay;
}
mapping(address => StakeStore[]) public stakeLists;
/* Temporary state for calculating daily rounds */
struct DailyRoundState {
uint256 _allocSupplyCached;
uint256 _payoutTotal;
}
struct XfLobbyEntryStore {
uint96 rawAmount;
address referrerAddr;
}
struct XfLobbyQueueStore {
uint40 headIndex;
uint40 tailIndex;
mapping(uint256 => XfLobbyEntryStore) entries;
}
mapping(uint256 => uint256) public xfLobby;
mapping(uint256 => mapping(address => XfLobbyQueueStore)) public xfLobbyMembers;
/**
* @dev PUBLIC FACING: Optionally update daily data for a smaller
* range to reduce gas cost for a subsequent operation
* @param beforeDay Only update days before this day number (optional; 0 for current day)
*/
function dailyDataUpdate(uint256 beforeDay)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Skip pre-claim period */
require(g._currentDay > CLAIM_PHASE_START_DAY, "E2X: Too early");
if (beforeDay != 0) {
require(beforeDay <= g._currentDay, "E2X: beforeDay cannot be in the future");
_dailyDataUpdate(g, beforeDay, false);
} else {
/* Default to updating before current day */
_dailyDataUpdate(g, g._currentDay, false);
}
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of daily data with
* a single call.
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return array of day stake shares total
* @return array of day payout total
*/
function dailyDataRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory _dayStakeSharesTotal, uint256[] memory _dayPayoutTotal, uint256[] memory _dayDividends)
{
require(beginDay < endDay && endDay <= globals.dailyDataCount, "E2X: range invalid");
_dayStakeSharesTotal = new uint256[](endDay - beginDay);
_dayPayoutTotal = new uint256[](endDay - beginDay);
_dayDividends = new uint256[](endDay - beginDay);
uint256 src = beginDay;
uint256 dst = 0;
do {
_dayStakeSharesTotal[dst] = uint256(dailyData[src].dayStakeSharesTotal);
_dayPayoutTotal[dst++] = uint256(dailyData[src].dayPayoutTotal);
_dayDividends[dst++] = dailyData[src].dayDividends;
} while (++src < endDay);
return (_dayStakeSharesTotal, _dayPayoutTotal, _dayDividends);
}
/**
* @dev PUBLIC FACING: External helper to return most global info with a single call.
* Ugly implementation due to limitations of the standard ABI encoder.
* @return Fixed array of values
*/
function globalInfo()
external
view
returns (uint256[10] memory)
{
return [
globals.lockedSunsTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
block.timestamp,
totalSupply(),
xfLobby[_currentDay()]
];
}
/**
* @dev PUBLIC FACING: ERC20 totalSupply() is the circulating supply and does not include any
* staked Suns. allocatedSupply() includes both.
* @return Allocated Supply in Suns
*/
function allocatedSupply()
external
view
returns (uint256)
{
return totalSupply() + globals.lockedSunsTotal;
}
/**
* @dev PUBLIC FACING: External helper for the current day number since launch time
* @return Current day number (zero-based)
*/
function currentDay()
external
view
returns (uint256)
{
return _currentDay();
}
uint256 Dday = 1;
function setDay(uint256 day) external {
Dday = day;
}
function _currentDay()
internal
view
returns (uint256)
{
if (block.timestamp < LAUNCH_TIME){
return 0;
}else{
return Dday;
}
}
function _dailyDataUpdateAuto(GlobalsCache memory g)
internal
{
_dailyDataUpdate(g, g._currentDay, true);
}
function _globalsLoad(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
view
{
g._lockedSunsTotal = globals.lockedSunsTotal;
g._nextStakeSharesTotal = globals.nextStakeSharesTotal;
g._shareRate = globals.shareRate;
g._stakePenaltyTotal = globals.stakePenaltyTotal;
g._dailyDataCount = globals.dailyDataCount;
g._stakeSharesTotal = globals.stakeSharesTotal;
g._latestStakeId = globals.latestStakeId;
g._currentDay = _currentDay();
_globalsCacheSnapshot(g, gSnapshot);
}
function _globalsCacheSnapshot(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
pure
{
gSnapshot._lockedSunsTotal = g._lockedSunsTotal;
gSnapshot._nextStakeSharesTotal = g._nextStakeSharesTotal;
gSnapshot._shareRate = g._shareRate;
gSnapshot._stakePenaltyTotal = g._stakePenaltyTotal;
gSnapshot._dailyDataCount = g._dailyDataCount;
gSnapshot._stakeSharesTotal = g._stakeSharesTotal;
gSnapshot._latestStakeId = g._latestStakeId;
}
function _globalsSync(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
{
if (g._lockedSunsTotal != gSnapshot._lockedSunsTotal
|| g._nextStakeSharesTotal != gSnapshot._nextStakeSharesTotal
|| g._shareRate != gSnapshot._shareRate
|| g._stakePenaltyTotal != gSnapshot._stakePenaltyTotal) {
globals.lockedSunsTotal = uint72(g._lockedSunsTotal);
globals.nextStakeSharesTotal = uint72(g._nextStakeSharesTotal);
globals.shareRate = uint40(g._shareRate);
globals.stakePenaltyTotal = uint72(g._stakePenaltyTotal);
}
if (g._dailyDataCount != gSnapshot._dailyDataCount
|| g._stakeSharesTotal != gSnapshot._stakeSharesTotal
|| g._latestStakeId != gSnapshot._latestStakeId) {
globals.dailyDataCount = uint16(g._dailyDataCount);
globals.stakeSharesTotal = uint72(g._stakeSharesTotal);
globals.latestStakeId = g._latestStakeId;
}
}
function _stakeLoad(StakeStore storage stRef, uint40 stakeIdParam, StakeCache memory st)
internal
view
{
/* Ensure caller's stakeIndex is still current */
require(stakeIdParam == stRef.stakeId, "E2X: stakeIdParam not in stake");
st._stakeId = stRef.stakeId;
st._stakedSuns = stRef.stakedSuns;
st._stakeShares = stRef.stakeShares;
st._lockedDay = stRef.lockedDay;
st._stakedDays = stRef.stakedDays;
st._unlockedDay = stRef.unlockedDay;
}
function _stakeUpdate(StakeStore storage stRef, StakeCache memory st)
internal
{
stRef.stakeId = st._stakeId;
stRef.stakedSuns = uint72(st._stakedSuns);
stRef.stakeShares = uint72(st._stakeShares);
stRef.lockedDay = uint16(st._lockedDay);
stRef.stakedDays = uint16(st._stakedDays);
stRef.unlockedDay = uint16(st._unlockedDay);
}
function _stakeAdd(
StakeStore[] storage stakeListRef,
uint40 newStakeId,
uint256 newStakedSuns,
uint256 newStakeShares,
uint256 newLockedDay,
uint256 newStakedDays
)
internal
{
stakeListRef.push(
StakeStore(
newStakeId,
uint72(newStakedSuns),
uint72(newStakeShares),
uint16(newLockedDay),
uint16(newStakedDays),
uint16(0) // unlockedDay
)
);
}
/**
* @dev Efficiently delete from an unordered array by moving the last element
* to the "hole" and reducing the array length. Can change the order of the list
* and invalidate previously held indexes.
* @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd()
* @param stakeListRef Reference to stakeLists[stakerAddr] array in storage
* @param stakeIndex Index of the element to delete
*/
function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex)
internal
{
uint256 lastIndex = stakeListRef.length - 1;
/* Skip the copy if element to be removed is already the last element */
if (stakeIndex != lastIndex) {
/* Copy last element to the requested element's "hole" */
stakeListRef[stakeIndex] = stakeListRef[lastIndex];
}
/*
Reduce the array length now that the array is contiguous.
Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex'
*/
stakeListRef.pop();
}
/**
* @dev Estimate the stake payout for an incomplete day
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param day Day to calculate bonuses for
* @return Payout in Suns
*/
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day)
internal
view
returns (uint256 payout)
{
/* Prevent updating state for this estimation */
GlobalsCache memory gTmp;
_globalsCacheSnapshot(g, gTmp);
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedSunsTotal;
_dailyRoundCalc(gTmp, rs, day);
/* Stake is no longer locked so it must be added to total as if it were */
gTmp._stakeSharesTotal += stakeSharesParam;
payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal;
return payout;
}
function _dailyRoundCalc(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
view
{
/*
Calculate payout round
Inflation of 5.42% inflation per 364 days (approx 1 year)
dailyInterestRate = exp(log(1 + 5.42%) / 364) - 1
= exp(log(1 + 0.0542) / 364) - 1
= exp(log(1.0542) / 364) - 1
= 0.0.00014523452066 (approx)
payout = allocSupply * dailyInterestRate
= allocSupply / (1 / dailyInterestRate)
= allocSupply / (1 / 0.00014523452066)
= allocSupply / 6885.4153644438375 (approx)
= allocSupply * 50000 / 68854153 (* 50000/50000 for int precision)
*/
rs._payoutTotal = (rs._allocSupplyCached * 50000 / 68854153);
if (g._stakePenaltyTotal != 0) {
rs._payoutTotal += g._stakePenaltyTotal;
g._stakePenaltyTotal = 0;
}
}
function _dailyRoundCalcAndStore(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
{
_dailyRoundCalc(g, rs, day);
dailyData[day].dayPayoutTotal = uint72(rs._payoutTotal);
dailyData[day].dayDividends = xfLobby[day];
dailyData[day].dayStakeSharesTotal = uint72(g._stakeSharesTotal);
}
function _dailyDataUpdate(GlobalsCache memory g, uint256 beforeDay, bool isAutoUpdate)
private
{
if (g._dailyDataCount >= beforeDay) {
/* Already up-to-date */
return;
}
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedSunsTotal;
uint256 day = g._dailyDataCount;
_dailyRoundCalcAndStore(g, rs, day);
/* Stakes started during this day are added to the total the next day */
if (g._nextStakeSharesTotal != 0) {
g._stakeSharesTotal += g._nextStakeSharesTotal;
g._nextStakeSharesTotal = 0;
}
while (++day < beforeDay) {
_dailyRoundCalcAndStore(g, rs, day);
}
emit DailyDataUpdate(
msg.sender,
block.timestamp,
g._dailyDataCount,
day
);
g._dailyDataCount = day;
}
}
contract StakeableToken is GlobalsAndUtility {
/**
* @dev PUBLIC FACING: Open a stake.
* @param newStakedSuns Number of Suns to stake
* @param newStakedDays Number of days to stake
*/
function stakeStart(uint256 newStakedSuns, uint256 newStakedDays)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Enforce the minimum stake time */
require(newStakedDays >= MIN_STAKE_DAYS, "E2X: newStakedDays lower than minimum");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
_stakeStart(g, newStakedSuns, newStakedDays);
/* Remove staked Suns from balance of staker */
_burn(msg.sender, newStakedSuns);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty
* immediately. The staker must still call stakeEnd() to retrieve their stake return (if any).
* @param stakerAddr Address of staker
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* require() is more informative than the default assert() */
require(stakeLists[stakerAddr].length != 0, "E2X: Empty stake list");
require(stakeIndex < stakeLists[stakerAddr].length, "E2X: stakeIndex invalid");
StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex];
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stRef, stakeIdParam, st);
/* Stake must have served full term */
require(g._currentDay >= st._lockedDay + st._stakedDays, "E2X: Stake not fully served");
/* Stake must still be locked */
require(st._unlockedDay == 0, "E2X: Stake already unlocked");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Unlock the completed stake */
_stakeUnlock(g, st);
/* stakeReturn & dividends values are unused here */
(, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty) = _stakePerformance(
g,
st,
st._stakedDays
);
emit StakeGoodAccounting(
stakeIdParam,
stakerAddr,
msg.sender,
st._stakedSuns,
st._stakeShares,
payout,
penalty
);
if (cappedPenalty != 0) {
g._stakePenaltyTotal += cappedPenalty;
}
/* st._unlockedDay has changed */
_stakeUpdate(stRef, st);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so
* a stake id is used to reject stale indexes.
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
StakeStore[] storage stakeListRef = stakeLists[msg.sender];
/* require() is more informative than the default assert() */
require(stakeListRef.length != 0, "E2X: Empty stake list");
require(stakeIndex < stakeListRef.length, "E2X: stakeIndex invalid");
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stakeListRef[stakeIndex], stakeIdParam, st);
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
uint256 servedDays = 0;
bool prevUnlocked = (st._unlockedDay != 0);
uint256 stakeReturn;
uint256 payout = 0;
uint256 dividends = 0;
uint256 penalty = 0;
uint256 cappedPenalty = 0;
if (g._currentDay >= st._lockedDay) {
if (prevUnlocked) {
/* Previously unlocked in stakeGoodAccounting(), so must have served full term */
servedDays = st._stakedDays;
} else {
_stakeUnlock(g, st);
servedDays = g._currentDay - st._lockedDay;
if (servedDays > st._stakedDays) {
servedDays = st._stakedDays;
}
}
(stakeReturn, payout, dividends, penalty, cappedPenalty) = _stakePerformance(g, st, servedDays);
msg.sender.transfer(dividends);
} else {
/* Stake hasn't been added to the total yet, so no penalties or rewards apply */
g._nextStakeSharesTotal -= st._stakeShares;
stakeReturn = st._stakedSuns;
}
emit StakeEnd(
stakeIdParam,
prevUnlocked ? 1 : 0,
msg.sender,
st._lockedDay,
servedDays,
st._stakedSuns,
st._stakeShares,
dividends,
payout,
penalty,
stakeReturn
);
if (cappedPenalty != 0 && !prevUnlocked) {
/* Split penalty proceeds only if not previously unlocked by stakeGoodAccounting() */
g._stakePenaltyTotal += cappedPenalty;
}
/* Pay the stake return, if any, to the staker */
if (stakeReturn != 0) {
_mint(msg.sender, stakeReturn);
}
g._lockedSunsTotal -= st._stakedSuns;
_stakeRemove(stakeListRef, stakeIndex);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Return the current stake count for a staker address
* @param stakerAddr Address of staker
*/
function stakeCount(address stakerAddr)
external
view
returns (uint256)
{
return stakeLists[stakerAddr].length;
}
/**
* @dev Open a stake.
* @param g Cache of stored globals
* @param newStakedSuns Number of Suns to stake
* @param newStakedDays Number of days to stake
*/
function _stakeStart(
GlobalsCache memory g,
uint256 newStakedSuns,
uint256 newStakedDays
)
internal
{
/* Enforce the maximum stake time */
require(newStakedDays <= MAX_STAKE_DAYS, "E2X: newStakedDays higher than maximum");
uint256 bonusSuns = _stakeStartBonusSuns(newStakedSuns, newStakedDays);
uint256 newStakeShares = (newStakedSuns + bonusSuns) * SHARE_RATE_SCALE / g._shareRate;
/* Ensure newStakedSuns is enough for at least one stake share */
require(newStakeShares != 0, "E2X: newStakedSuns must be at least minimum shareRate");
/*
The stakeStart timestamp will always be part-way through the current
day, so it needs to be rounded-up to the next day to ensure all
stakes align with the same fixed calendar days. The current day is
already rounded-down, so rounded-up is current day + 1.
*/
uint256 newLockedDay = g._currentDay + 1;
/* Create Stake */
uint40 newStakeId = ++g._latestStakeId;
_stakeAdd(
stakeLists[msg.sender],
newStakeId,
newStakedSuns,
newStakeShares,
newLockedDay,
newStakedDays
);
emit StakeStart(
newStakeId,
msg.sender,
newStakedSuns,
newStakeShares,
newStakedDays
);
/* Stake is added to total in the next round, not the current round */
g._nextStakeSharesTotal += newStakeShares;
/* Track total staked Suns for inflation calculations */
g._lockedSunsTotal += newStakedSuns;
}
/**
* @dev Calculates total stake payout including rewards for a multi-day range
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param beginDay First day to calculate bonuses for
* @param endDay Last day (non-inclusive) of range to calculate bonuses for
* @return Payout in Suns
*/
function _calcPayoutRewards(
GlobalsCache memory g,
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
private
view
returns (uint256 payout)
{
uint256 counter;
for (uint256 day = beginDay; day < endDay; day++) {
uint256 dayPayout;
dayPayout = dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
if (counter < 4) {
counter++;
}
/* Eligible to receive bonus */
else {
dayPayout = (dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal) * BONUS_DAY_SCALE;
counter = 0;
}
payout += dayPayout;
}
return payout;
}
/**
* @dev Calculates user dividends
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param beginDay First day to calculate bonuses for
* @param endDay Last day (non-inclusive) of range to calculate bonuses for
* @return Payout in Suns
*/
function _calcPayoutDividendsReward(
GlobalsCache memory g,
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
private
view
returns (uint256 payout)
{
for (uint256 day = beginDay; day < endDay; day++) {
uint256 dayPayout;
/* user's share of 95% of the day's dividends */
dayPayout += ((dailyData[day].dayDividends * 90) / 100) * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
payout += dayPayout;
}
return payout;
}
/**
* @dev Calculate bonus Suns for a new stake, if any
* @param newStakedSuns Number of Suns to stake
* @param newStakedDays Number of days to stake
*/
function _stakeStartBonusSuns(uint256 newStakedSuns, uint256 newStakedDays)
private
pure
returns (uint256 bonusSuns)
{
/*
LONGER PAYS BETTER:
If longer than 1 day stake is committed to, each extra day
gives bonus shares of approximately 0.0548%, which is approximately 20%
extra per year of increased stake length committed to, but capped to a
maximum of 200% extra.
extraDays = stakedDays - 1
longerBonus% = (extraDays / 364) * 20%
= (extraDays / 364) / 5
= extraDays / 1820
= extraDays / LPB
extraDays = longerBonus% * 1820
extraDaysMax = longerBonusMax% * 1820
= 200% * 1820
= 3640
= LPB_MAX_DAYS
BIGGER PAYS BETTER:
Bonus percentage scaled 0% to 10% for the first 7M E2X of stake.
biggerBonus% = (cappedSuns / BPB_MAX_SUNS) * 10%
= (cappedSuns / BPB_MAX_SUNS) / 10
= cappedSuns / (BPB_MAX_SUNS * 10)
= cappedSuns / BPB
COMBINED:
combinedBonus% = longerBonus% + biggerBonus%
cappedExtraDays cappedSuns
= --------------- + ------------
LPB BPB
cappedExtraDays * BPB cappedSuns * LPB
= --------------------- + ------------------
LPB * BPB LPB * BPB
cappedExtraDays * BPB + cappedSuns * LPB
= --------------------------------------------
LPB * BPB
bonusSuns = suns * combinedBonus%
= suns * (cappedExtraDays * BPB + cappedSuns * LPB) / (LPB * BPB)
*/
uint256 cappedExtraDays = 0;
/* Must be more than 1 day for Longer-Pays-Better */
if (newStakedDays > 1) {
cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS;
}
uint256 cappedStakedSuns = newStakedSuns <= BPB_MAX_SUNS
? newStakedSuns
: BPB_MAX_SUNS;
bonusSuns = cappedExtraDays * BPB + cappedStakedSuns * LPB;
bonusSuns = newStakedSuns * bonusSuns / (LPB * BPB);
return bonusSuns;
}
function _stakeUnlock(GlobalsCache memory g, StakeCache memory st)
private
pure
{
g._stakeSharesTotal -= st._stakeShares;
st._unlockedDay = g._currentDay;
}
function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays)
private
view
returns (uint256 stakeReturn, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty)
{
if (servedDays < st._stakedDays) {
(payout, penalty) = _calcPayoutAndEarlyPenalty(
g,
st._lockedDay,
st._stakedDays,
servedDays,
st._stakeShares
);
stakeReturn = st._stakedSuns + payout;
dividends = _calcPayoutDividendsReward(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
} else {
// servedDays must == stakedDays here
payout = _calcPayoutRewards(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
dividends = _calcPayoutDividendsReward(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
stakeReturn = st._stakedSuns + payout;
penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn);
}
if (penalty != 0) {
if (penalty > stakeReturn) {
/* Cannot have a negative stake return */
cappedPenalty = stakeReturn;
stakeReturn = 0;
} else {
/* Remove penalty from the stake return */
cappedPenalty = penalty;
stakeReturn -= cappedPenalty;
}
}
return (stakeReturn, payout, dividends, penalty, cappedPenalty);
}
function _calcPayoutAndEarlyPenalty(
GlobalsCache memory g,
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 servedDays,
uint256 stakeSharesParam
)
private
view
returns (uint256 payout, uint256 penalty)
{
uint256 servedEndDay = lockedDayParam + servedDays;
/* 50% of stakedDays (rounded up) with a minimum applied */
uint256 penaltyDays = (stakedDaysParam + 1) / 2;
if (penaltyDays < EARLY_PENALTY_MIN_DAYS) {
penaltyDays = EARLY_PENALTY_MIN_DAYS;
}
if (servedDays == 0) {
/* Fill penalty days with the estimated average payout */
uint256 expected = _estimatePayoutRewardsDay(g, stakeSharesParam, lockedDayParam);
penalty = expected * penaltyDays;
return (payout, penalty); // Actual payout was 0
}
if (penaltyDays < servedDays) {
/*
Simplified explanation of intervals where end-day is non-inclusive:
penalty: [lockedDay ... penaltyEndDay)
delta: [penaltyEndDay ... servedEndDay)
payout: [lockedDay ....................... servedEndDay)
*/
uint256 penaltyEndDay = lockedDayParam + penaltyDays;
penalty = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, penaltyEndDay);
uint256 delta = _calcPayoutRewards(g, stakeSharesParam, penaltyEndDay, servedEndDay);
payout = penalty + delta;
return (payout, penalty);
}
/* penaltyDays >= servedDays */
payout = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, servedEndDay);
if (penaltyDays == servedDays) {
penalty = payout;
} else {
/*
(penaltyDays > servedDays) means not enough days served, so fill the
penalty days with the average payout from only the days that were served.
*/
penalty = payout * penaltyDays / servedDays;
}
return (payout, penalty);
}
function _calcLatePenalty(
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 unlockedDayParam,
uint256 rawStakeReturn
)
private
pure
returns (uint256)
{
/* Allow grace time before penalties accrue */
uint256 maxUnlockedDay = lockedDayParam + stakedDaysParam + LATE_PENALTY_GRACE_DAYS;
if (unlockedDayParam <= maxUnlockedDay) {
return 0;
}
/* Calculate penalty as a percentage of stake return based on time */
return rawStakeReturn * (unlockedDayParam - maxUnlockedDay) / LATE_PENALTY_SCALE_DAYS;
}
}
contract TransformableToken is StakeableToken {
/**
* @dev PUBLIC FACING: Enter the auction lobby for the current round
* @param referrerAddr TRX address of referring user (optional; 0x0 for no referrer)
*/
function xfLobbyEnter(address referrerAddr)
external
payable
{
uint256 enterDay = _currentDay();
uint256 rawAmount = msg.value;
require(rawAmount != 0, "E2X: Amount required");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 entryIndex = qRef.tailIndex++;
qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);
xfLobby[enterDay] += rawAmount;
emit XfLobbyEnter(
block.timestamp,
enterDay,
entryIndex,
rawAmount
);
}
/**
* @dev PUBLIC FACING: Leave the transform lobby after the round is complete
* @param enterDay Day number when the member entered
* @param count Number of queued-enters to exit (optional; 0 for all)
*/
function xfLobbyExit(uint256 enterDay, uint256 count)
external
{
require(enterDay < _currentDay(), "E2X: Round is not complete");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 headIndex = qRef.headIndex;
uint256 endIndex;
if (count != 0) {
require(count <= qRef.tailIndex - headIndex, "E2X: count invalid");
endIndex = headIndex + count;
} else {
endIndex = qRef.tailIndex;
require(headIndex < endIndex, "E2X: count invalid");
}
uint256 waasLobby = _waasLobby(enterDay);
uint256 _xfLobby = xfLobby[enterDay];
uint256 totalXfAmount = 0;
do {
uint256 rawAmount = qRef.entries[headIndex].rawAmount;
address referrerAddr = qRef.entries[headIndex].referrerAddr;
delete qRef.entries[headIndex];
uint256 xfAmount = waasLobby * rawAmount / _xfLobby;
if (referrerAddr == address(0) || referrerAddr == msg.sender) {
/* No referrer or Self-referred */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referral bonus of 5% of xfAmount to member */
uint256 referralBonusSuns = xfAmount / 20;
xfAmount += referralBonusSuns;
/* Then a cumulative referrer bonus of 10% to referrer */
uint256 referrerBonusSuns = xfAmount / 10;
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
_mint(referrerAddr, referrerBonusSuns);
}
totalXfAmount += xfAmount;
} while (++headIndex < endIndex);
qRef.headIndex = uint40(headIndex);
if (totalXfAmount != 0) {
_mint(msg.sender, totalXfAmount);
}
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of xfLobby[] with
* a single call
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of values
*/
function xfLobbyRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(
beginDay < endDay && endDay <= _currentDay(),
"E2X: invalid range"
);
list = new uint256[](endDay - beginDay);
uint256 src = beginDay;
uint256 dst = 0;
do {
list[dst++] = uint256(xfLobby[src++]);
} while (src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: Release 5% dev share from daily dividends
*/
function xfFlush()
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
require(address(this).balance != 0, "E2X: No value");
require(LAST_FLUSHED_DAY < _currentDay(), "E2X: Invalid day");
_dailyDataUpdateAuto(g);
FLUSH_ADDR.transfer((dailyData[LAST_FLUSHED_DAY].dayDividends * 4) / 100);
T2X_SHARE_ADDR.transfer((dailyData[LAST_FLUSHED_DAY].dayDividends * 6) / 100);
LAST_FLUSHED_DAY++;
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Return a current lobby member queue entry.
* Only needed due to limitations of the standard ABI encoder.
* @param memberAddr TRX address of the lobby member
* @param enterDay
* @param entryIndex
* @return 1: Raw amount that was entered with; 2: Referring TRX addr (optional; 0x0 for no referrer)
*/
function xfLobbyEntry(address memberAddr, uint256 enterDay, uint256 entryIndex)
external
view
returns (uint256 rawAmount, address referrerAddr)
{
XfLobbyEntryStore storage entry = xfLobbyMembers[enterDay][memberAddr].entries[entryIndex];
require(entry.rawAmount != 0, "E2X: Param invalid");
return (entry.rawAmount, entry.referrerAddr);
}
/**
* @dev PUBLIC FACING: Return the lobby days that a user is in with a single call
* @param memberAddr TRX address of the user
* @return Bit vector of lobby day numbers
*/
function xfLobbyPendingDays(address memberAddr)
external
view
returns (uint256[XF_LOBBY_DAY_WORDS] memory words)
{
uint256 day = _currentDay() + 1;
while (day-- != 0) {
if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) {
words[day >> 8] |= 1 << (day & 255);
}
}
return words;
}
function _waasLobby(uint256 enterDay)
private
returns (uint256 waasLobby)
{
/* 1342465753424 = ~ 4900000 * SUNS_PER_E2X / 365 */
if (enterDay > 0 && enterDay <= 365) {
waasLobby = CLAIM_STARTING_AMOUNT - ((enterDay - 1) * 1342465753424);
} else {
waasLobby = CLAIM_LOWEST_AMOUNT;
}
return waasLobby;
}
function _emitXfLobbyExit(
uint256 enterDay,
uint256 entryIndex,
uint256 xfAmount,
address referrerAddr
)
private
{
emit XfLobbyExit(
block.timestamp,
enterDay,
entryIndex,
xfAmount,
referrerAddr
);
}
}
contract E2X is TransformableToken {
constructor()
public
{
/* Initialize global shareRate to 1 */
globals.shareRate = uint40(1 * SHARE_RATE_SCALE);
}
function() external payable {}
} | * @dev PUBLIC FACING: Enter the auction lobby for the current round @param referrerAddr TRX address of referring user (optional; 0x0 for no referrer)/ | {
uint256 enterDay = _currentDay();
uint256 rawAmount = msg.value;
require(rawAmount != 0, "E2X: Amount required");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 entryIndex = qRef.tailIndex++;
qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);
xfLobby[enterDay] += rawAmount;
emit XfLobbyEnter(
block.timestamp,
enterDay,
entryIndex,
rawAmount
);
}
| 2,179,810 | [
1,
14939,
478,
2226,
1360,
30,
15439,
326,
279,
4062,
22925,
1637,
364,
326,
783,
3643,
225,
14502,
3178,
4235,
60,
1758,
434,
1278,
20245,
729,
261,
10444,
31,
374,
92,
20,
364,
1158,
14502,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
2254,
5034,
6103,
4245,
273,
389,
2972,
4245,
5621,
203,
203,
3639,
2254,
5034,
1831,
6275,
273,
1234,
18,
1132,
31,
203,
3639,
2583,
12,
1899,
6275,
480,
374,
16,
315,
41,
22,
60,
30,
16811,
1931,
8863,
203,
203,
3639,
1139,
74,
48,
947,
1637,
3183,
2257,
2502,
1043,
1957,
273,
16128,
48,
947,
1637,
6918,
63,
2328,
4245,
6362,
3576,
18,
15330,
15533,
203,
203,
3639,
2254,
5034,
1241,
1016,
273,
1043,
1957,
18,
13101,
1016,
9904,
31,
203,
203,
3639,
1043,
1957,
18,
8219,
63,
4099,
1016,
65,
273,
1139,
74,
48,
947,
1637,
1622,
2257,
12,
11890,
10525,
12,
1899,
6275,
3631,
14502,
3178,
1769,
203,
203,
3639,
16128,
48,
947,
1637,
63,
2328,
4245,
65,
1011,
1831,
6275,
31,
203,
203,
3639,
3626,
1139,
74,
48,
947,
1637,
10237,
12,
203,
5411,
1203,
18,
5508,
16,
7010,
5411,
6103,
4245,
16,
7010,
5411,
1241,
1016,
16,
7010,
5411,
1831,
6275,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import './IVideoBase.sol';
import './VideoBaseAccessor.sol';
contract VideoCreator
is
VideoBaseAccessor
{
using SafeMath for uint256;
/*** STORAGE ***/
/// @dev Cost in weis for propose a new video.
uint256 public newVideoCost = 0.0001 ether;
/// @dev Cost in weis for update a video.
uint256 public videoUpdateCost = 0.0001 ether;
/*** EVENTS ***/
/// @dev Emitted when a new video is proposed to added. To be captured by
/// an oracle which imports the video.
/// @param videoId new video id proposed.
event NewVideoProposed(bytes32 videoId);
/// @dev Emitted when an existing video is requested to be updated. To be
/// captured by an oracle which updates the video.
/// @param videoId video id requested.
event VideoUpdateRequested(bytes32 videoId);
/// @dev propose to add a video, must be a new video. Emitting
/// NewVideoProposed event for the oracle to add a new video.
/// Payable to the videoBase owner and payee, and free for the owner and
/// board members.
/// @param videoId to be proposed as a new video.
function proposeNewVideo(bytes32 videoId)
public
payable
whenVideoBaseNotPaused
onlyVideoBaseNewVideo(videoId)
{
uint256 _cost = newVideoCost;
if (videoBase.owner() == msg.sender ||
videoBase.findBoardMember(msg.sender) >= 0) {
_cost = 0; // free for the owner and board members.
}
require(msg.value >= _cost);
uint256 senderRemaining = msg.value.sub(_cost);
uint256 payeeSplit = getPayeeSplit(_cost);
NewVideoProposed(videoId);
if (_cost > 0) {
if (payeeSplit > 0) {
payee.transfer(payeeSplit);
}
videoBase.owner().transfer(_cost - payeeSplit);
}
msg.sender.transfer(senderRemaining);
}
/// @dev actually add a new video, usually proposed by the owner/board member
/// and added by a system account.
/// @param videoId to be proposed as a new video.
/// @param viewCount fetched from the video platform.
function addNewVideo(bytes32 videoId, uint256 viewCount)
public
onlyVideoBaseSystemAccounts
whenVideoBaseNotPaused
onlyVideoBaseNewVideo(videoId) {
videoBase.addNewVideoTrusted(videoBase.owner(), videoId, viewCount);
}
/// @dev request to update a video, must be an existing video.
/// Emitting updateVideoRequested event for the oracle to update an
/// existing video. Only the video's owner is allowed to request.
/// payable to the videoBase owner and payee.
/// @param tokenId of the video to be requested.
function requestVideoUpdate(uint256 tokenId)
public
payable
onlyVideoBaseTokenOwnerOf(tokenId)
whenVideoBaseNotPaused
{
require(msg.value >= videoUpdateCost);
uint256 senderRemaining = msg.value.sub(videoUpdateCost);
uint256 payeeSplit = getPayeeSplit(videoUpdateCost);
VideoUpdateRequested(videoBase.getVideoId(tokenId));
if (payeeSplit > 0) {
payee.transfer(payeeSplit);
}
videoBase.owner().transfer(videoUpdateCost - payeeSplit);
msg.sender.transfer(senderRemaining);
}
/// @dev actually update an existing video, usually requested by the video's
/// owner and updated by a system account.
/// @param videoId to be requested For an update.
/// @param viewCount fetched from the video platform.
function updateVideo(bytes32 videoId, uint256 viewCount)
public
onlyVideoBaseSystemAccounts
whenVideoBaseNotPaused
onlyVideoBaseExistingVideo(videoId) {
videoBase.updateVideoTrusted(videoId, viewCount);
}
/// @dev set newVideoCost in wei, only by videoBase onwer.
/// @param _newCost in wei.
function setNewVideoCost(uint256 _newCost)
public
onlyVideoBaseOwner {
require(address(videoBase) != address(0));
newVideoCost = _newCost;
}
/// @dev set videoUpdateCost in wei, only by videoBase onwer.
/// @param _newCost in wei.
function setVideoUpdateCost(uint256 _newCost)
public
onlyVideoBaseOwner {
require(address(videoBase) != address(0));
videoUpdateCost = _newCost;
}
}
| ** STORAGE ***/ @dev Cost in weis for propose a new video. @dev Cost in weis for update a video.** EVENTS ***/ @dev Emitted when a new video is proposed to added. To be captured by an oracle which imports the video. @param videoId new video id proposed. @dev Emitted when an existing video is requested to be updated. To be captured by an oracle which updates the video. @param videoId video id requested. @dev propose to add a video, must be a new video. Emitting NewVideoProposed event for the oracle to add a new video. Payable to the videoBase owner and payee, and free for the owner and board members. @param videoId to be proposed as a new video. | {
uint256 _cost = newVideoCost;
if (videoBase.owner() == msg.sender ||
videoBase.findBoardMember(msg.sender) >= 0) {
}
require(msg.value >= _cost);
uint256 senderRemaining = msg.value.sub(_cost);
uint256 payeeSplit = getPayeeSplit(_cost);
NewVideoProposed(videoId);
if (_cost > 0) {
if (payeeSplit > 0) {
payee.transfer(payeeSplit);
}
videoBase.owner().transfer(_cost - payeeSplit);
}
msg.sender.transfer(senderRemaining);
}
| 895,960 | [
1,
19009,
342,
282,
28108,
316,
732,
291,
364,
450,
4150,
279,
394,
6191,
18,
282,
28108,
316,
732,
291,
364,
1089,
279,
6191,
18,
9964,
55,
342,
225,
512,
7948,
1347,
279,
394,
6191,
353,
20084,
358,
3096,
18,
2974,
506,
19550,
635,
282,
392,
20865,
1492,
10095,
326,
6191,
18,
225,
6191,
548,
394,
6191,
612,
20084,
18,
225,
512,
7948,
1347,
392,
2062,
6191,
353,
3764,
358,
506,
3526,
18,
2974,
506,
282,
19550,
635,
392,
20865,
1492,
4533,
326,
6191,
18,
225,
6191,
548,
6191,
612,
3764,
18,
225,
450,
4150,
358,
527,
279,
6191,
16,
1297,
506,
279,
394,
6191,
18,
16008,
1787,
282,
1166,
10083,
626,
7423,
871,
364,
326,
20865,
358,
527,
279,
394,
6191,
18,
282,
13838,
429,
358,
326,
6191,
2171,
3410,
471,
8843,
1340,
16,
471,
4843,
364,
326,
3410,
471,
282,
11094,
4833,
18,
225,
6191,
548,
358,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
1377,
288,
203,
565,
2254,
5034,
389,
12398,
273,
394,
10083,
8018,
31,
203,
565,
309,
261,
9115,
2171,
18,
8443,
1435,
422,
1234,
18,
15330,
747,
203,
3639,
6191,
2171,
18,
4720,
22233,
4419,
12,
3576,
18,
15330,
13,
1545,
374,
13,
288,
203,
565,
289,
203,
565,
2583,
12,
3576,
18,
1132,
1545,
389,
12398,
1769,
203,
565,
2254,
5034,
5793,
11429,
273,
1234,
18,
1132,
18,
1717,
24899,
12398,
1769,
203,
565,
2254,
5034,
8843,
1340,
5521,
273,
1689,
528,
1340,
5521,
24899,
12398,
1769,
203,
565,
1166,
10083,
626,
7423,
12,
9115,
548,
1769,
203,
203,
565,
309,
261,
67,
12398,
405,
374,
13,
288,
203,
1377,
309,
261,
10239,
1340,
5521,
405,
374,
13,
288,
203,
3639,
8843,
1340,
18,
13866,
12,
10239,
1340,
5521,
1769,
203,
1377,
289,
203,
1377,
6191,
2171,
18,
8443,
7675,
13866,
24899,
12398,
300,
8843,
1340,
5521,
1769,
203,
565,
289,
203,
565,
1234,
18,
15330,
18,
13866,
12,
15330,
11429,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// File: contracts/IWoofpackNFTToken.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IWoofpackNFTToken {
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
function transferOwnership(address newOwner) external;
function renounceMinter() external;
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
function mint(address recipient, uint256 mintAmount) external returns (bool);
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (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: contracts/utils/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
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) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// 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;
}
}
// File: contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. 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 Context, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
IWoofpackNFTToken private _token;
// Amount of wei raised
uint256 private _weiRaised;
// Address where funds are collected
address payable private _wallet;
// Private Sale price is 0.06 ETH
uint256 internal _rate = 60000000000000000;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 mintAmount);
/**
* @param __wallet Address where collected funds will be forwarded to
* @param __token Address of the token being sold
*/
constructor (address payable __wallet, IWoofpackNFTToken __token) public {
require(__wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(__token) != address(0), "Crowdsale: token is the zero address");
_wallet = __wallet;
_token = __token;
}
/**
* @return the token being sold.
*/
function token() public view virtual returns (IWoofpackNFTToken) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view virtual returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view virtual returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view virtual returns (uint256) {
return _weiRaised;
}
/**
* @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
**/
function buyNFT(address beneficiary, uint256 mintAmount) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, mintAmount, weiAmount);
// update state ETH Amount
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, mintAmount);
emit TokensPurchased(_msgSender(), beneficiary, mintAmount);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds(beneficiary, weiAmount);
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param mintAmount total no of tokens to be minted
* @param weiAmount no of ETH sent
*/
function _preValidatePurchase(address beneficiary, uint256 mintAmount, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @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 mintAmount Total mint tokens
*/
function _processPurchase(address beneficiary, uint256 mintAmount) internal virtual {
_deliverTokens(beneficiary, mintAmount);
}
/**
* @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 mintAmount Total mint tokens
*/
function _deliverTokens(address beneficiary, uint256 mintAmount) internal {
/*********** COMMENTED REQUIRE BECAUSE IT WAS RETURNING BOOLEAN AND WE WERE LISTENING FROM THE INTERFACE THAT IT WILL RETURN BOOLEAN BUT IT REVERTS OUR TRANSACTION**************** */
// Potentially dangerous assumption about the type of the token.
require(
token().mint(beneficiary, mintAmount)
, "Crowdsale: transfer failed"
);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(address /*beneficiary*/, uint256 /*weiAmount*/) internal virtual {
_wallet.transfer(msg.value);
}
/**
* @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 weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/roles/Roles.sol
// pragma solidity ^0.5.0;
pragma solidity ^0.8.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/roles/WhitelistAdminRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
abstract contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: contracts/roles/WhitelistedRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: contracts/crowdsale/validation/TimedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
abstract contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _openingTime;
uint256 private _closingTime;
uint256 private _secondarySaleTime;
/**
* Event for crowdsale extending
* @param newClosingTime new closing time
* @param prevClosingTime old closing time
*/
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "TimedCrowdsale: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param __openingTime Crowdsale opening time
* @param __closingTime Crowdsale closing time
* @param __secondarySaleTime Crowdsale secondary time
*/
constructor (uint256 __openingTime, uint256 __secondarySaleTime, uint256 __closingTime) {
// solhint-disable-next-line not-rely-on-time
require(__openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
// solhint-disable-next-line max-line-length
require(__secondarySaleTime > __openingTime, "TimedCrowdsale: opening time is not before secondary sale time");
// solhint-disable-next-line max-line-length
require(__closingTime > __secondarySaleTime, "TimedCrowdsale: secondary sale time is not before closing time");
_openingTime = __openingTime;
_closingTime = __closingTime;
_secondarySaleTime = __secondarySaleTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view virtual returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view virtual returns (uint256) {
return _closingTime;
}
/**
* @return the crowdsale secondary sale time.
*/
function secondaryTime() public view virtual returns (uint256) {
return _secondarySaleTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
function _extendTime(uint256 newClosingTime) internal virtual {
require(!hasClosed(), "TimedCrowdsale: already closed");
// solhint-disable-next-line max-line-length
require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
_closingTime = newClosingTime;
}
}
// File: contracts/crowdsale/validation/CappedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
abstract contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _cap;
uint256 internal _minted;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param cap Max amount of wei to be contributed
*/
constructor (uint256 cap) {
require(cap > 0, "CappedCrowdsale: cap is 0");
_cap = cap;
}
/**
* @return the cap of the crowdsale.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @return the minted of the crowdsale.
*/
function minted() public view returns (uint256) {
return _minted;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return _minted >= _cap;
}
function incrementMinted(uint256 amountOfTokens) internal virtual {
_minted += amountOfTokens;
}
function currentMinted() public view returns (uint256) {
return _minted;
}
}
// File: contracts/WoofpackNFTICO.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract WoofpackNFTICO is
Crowdsale,
CappedCrowdsale,
TimedCrowdsale,
Ownable,
WhitelistedRole
{
using SafeMath for uint256;
/* Track investor contributions */
uint256 public investorHardCap = 7; // 7 NFT
mapping(address => uint256) public contributions;
/* Crowdsale Stages */
enum CrowdsaleStage {
PreICO,
ICO
}
/* Default to presale stage */
CrowdsaleStage public stage = CrowdsaleStage.PreICO;
constructor(
address payable _wallet,
IWoofpackNFTToken _token,
uint256 _cap,
uint256 _openingTime,
uint256 _secondarySaleTime,
uint256 _closingTime
)
public
Crowdsale(_wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _secondarySaleTime, _closingTime)
{}
/**
* @dev Returns the amount contributed so far by a sepecific user.
* @param _beneficiary Address of contributor
* @return User contribution so far
*/
function getUserContribution(address _beneficiary)
public
view
returns (uint256)
{
return contributions[_beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect investor min/max funding cap.
* @param _beneficiary Token purchaser
*/
function _preValidatePurchase(address _beneficiary, uint256 mintAmount, uint256 weiAmount)
internal virtual override onlyWhileOpen
{
// Check how many NFT are minted
incrementMinted(mintAmount);
require(currentMinted() <= _cap, "WoofpackNFTICO: cap exceeded");
require(weiAmount.div(mintAmount) == rate(), "WoofpackNFTICO: Invalid ETH Amount");
// Validate inputs
require(weiAmount != 0, "WoofpackNFTICO: ETH sent 0");
require(_beneficiary != address(0), "WoofpackNFTICO: beneficiary zero address");
if (stage == CrowdsaleStage.PreICO) {
require(
isWhitelisted(_msgSender()),
"WoofpackNFTICO: Wallet Address is not WhiteListed"
);
}
// Check max minting limit
uint256 _existingContribution = contributions[_beneficiary];
uint256 _newContribution = _existingContribution.add(mintAmount);
require(
_newContribution <= investorHardCap,
"WoofpackNFTICO: No of Mint MaxCap"
);
contributions[_beneficiary] = _newContribution;
}
function extendTime(uint256 closingTime) public virtual onlyOwner {
_extendTime(closingTime);
}
/**
* @dev If goal is Reached then change to change to ICO Stage
* etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)
internal virtual override
{
if (block.timestamp >= secondaryTime() && stage == CrowdsaleStage.PreICO ) {
stage = CrowdsaleStage.ICO;
_rate = 70000000000000000; // 0.08ETH
_openingTime = secondaryTime(); // Set opening time to secondary time
}
super._updatePurchasingState(_beneficiary, _weiAmount);
}
/**
* @dev enables token transfers, called when owner calls finalize()
*/
function finalization() public onlyOwner {
token().renounceMinter();
}
} | * @dev Determines how ETH is stored/forwarded on purchases./ | function _forwardFunds(address /*beneficiary*/, uint256 /*weiAmount*/) internal virtual {
_wallet.transfer(msg.value);
}
| 2,234,320 | [
1,
10114,
3661,
512,
2455,
353,
4041,
19,
1884,
11804,
603,
5405,
343,
3304,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
11565,
42,
19156,
12,
2867,
1748,
70,
4009,
74,
14463,
814,
5549,
16,
2254,
5034,
1748,
1814,
77,
6275,
5549,
13,
2713,
5024,
288,
203,
3639,
389,
19177,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x46419008e8C16e5d66B1A51cC1f790017E8EacD5/sources/BZB.sol | * Retrieve the tokens owned by the caller./ | function myTokens()
public
view
returns(uint256)
{
address bzbHolderInternal = msg.sender;
return balanceOf(bzbHolderInternal);
}
| 3,472,880 | [
1,
5767,
326,
2430,
16199,
635,
326,
4894,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3399,
5157,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
11890,
5034,
13,
203,
565,
288,
203,
3639,
1758,
24788,
70,
6064,
3061,
273,
1234,
18,
15330,
31,
203,
3639,
327,
11013,
951,
12,
25292,
70,
6064,
3061,
1769,
203,
565,
289,
203,
27699,
27699,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0e20655885C38b1b5CEDfFF5b15289b76F3CdefC/sources/FounderSociety.sol | * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length./ | function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
}
| 15,739,733 | [
1,
5692,
279,
1375,
11890,
5034,
68,
358,
2097,
11768,
1375,
1080,
68,
20070,
4335,
598,
5499,
769,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18272,
12,
11890,
5034,
460,
16,
2254,
5034,
769,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
import "./RoleManager.sol";
import "./TokenManager.sol";
//This contracts handles the trip logic and acts as a platform contract owning the TokenManager contract and the RoleManager contract
contract PlatformContract
{
offer[] tripArray; //each trip offer by a lessor is stored in this array
uint256[] indexOfID; //0 means offer got deleted
RoleManager roleManager; //roleManager contract associated to this platform contract
TokenManager tokenManager; //tokenManager contract associated to this platform contract
mapping (address => user) public usermap; //can rent or subrent objects
//Verifier Section
//calling neccessary modifiers to implement the trip logic from the subclass
//Every role issue not directly related to trips is exclusively handeled in the subclass
modifier onlyVerifiedRenter(uint8 objectType) {
require (roleManager.isVerifiedRenter(msg.sender, objectType) == true);
_;
}
//objectType descirbes the sharing object category (car, charging station, bike, ...)
modifier onlyVerifiedLessor(uint8 objectType) {
require (roleManager.isVerifiedLessor(msg.sender, objectType) == true);
_;
}
modifier onlyVerifiers()
{
require (roleManager.isVerifier(msg.sender) == true);
_;
}
//renters who fail to pay for a trip have limited action right on the paltform
modifier onlyWithoutDebt()
{
require (tokenManager.hasDebt(msg.sender) == 0);
_;
}
modifier onlyAuthorities()
{
require (roleManager.isAuthority(msg.sender) == true);
_;
}
//renters or lessors which violated laws or acted in a malicious way can be blocked by authorities
modifier isNotBlockedRenter()
{
require (roleManager.isBlocked(msg.sender, false) == false);
_;
}
modifier isNotBlockedLessor()
{
require (roleManager.isBlocked(msg.sender, true) == false);
_;
}
//Each offer issued by a verified lessor needs to provide the following attributes
struct offer //offer cant be reserved while its started
{
address lessor; //lessor of the rental object
uint256 startTime; //start time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt
uint256 endTime; //end time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt
uint64 latpickupLocation; //lattitude of rental object pcikup location
uint64 longpickupLocation; //longitude of rental object pcikup location
uint64[10] latPolygons;
uint64[10] longPolygons; // at most 10 lattitude and longitude points to define return area of rental object
address renter; //renter of the object
bool reserved; //Is a trip reserved?
uint256 reservedBlockNumber; //BlockNumber when a trip got reserved
uint256 maxReservedAmount; //max amount of reservation time allowed in blocknumbers
bool readyToUse; //Lessor needs to state if the device is ready for use (unlockable, ...) so that the renter does not need to pay for waiting
//bool locked; //user might want to lock the object (car,..) during a trip to unlock it later (maybe not needed to be handled on chain but rather by interacting with the device itself)
uint256 started; //Block number of start time, 0 by default -> acts as a bool check
uint256 userDemandsEnd; //Block number of end demand
uint256 id; //Uid of the trip
uint256 price; //price in tokens per block (5 secs)
uint8 objectType; //car, charging station, ...
string model; //further information like BMW i3, Emmy Vesper, can be also used to present a more accurate picture to the user in the app
}
//users can be lessors or renters
struct user
{
bool reserved; //did the user reserve a trip? -> maybe increase to a limit of multiple trips(?)
bool started; //did the user start a trip?
uint256 rating; //Review Rating for that user from 1-5 on Client side -> possible future feature that lessors can also rate renters and trips may automatically reject low rated renters
uint256 ratingCount; //how often has this user been rated? Used to calculate rating
mapping(address => bool) hasRatingRight; //checks if user has the right to give a 1-5 star rating for a trip lessor (1 right for each ended trip)
mapping(address => bool) hasReportRight; //checks if the user has the right to give a report for a trip lessor
}
//description: how do you want to name the first token?
constructor(string memory description) public {
roleManager = new RoleManager(msg.sender); //creating a new instance of a subcontract in the parent class //Initializes first authority when contract is created
tokenManager = new TokenManager();
tokenManager.createNewToken(msg.sender,description); //Genesis Token/ First Token
offer memory temp; //Genesis offer, cant be booked
tripArray.push(temp);
indexOfID.push(0); //0 id, indicates that trip got deleted, never used for an existing trip, points to Genesis trip
}
//authorities who want to interact with the On Chain Governance need the address of the created local instance of the RoleManager contract
function getRoleManagerAddress() public view returns(address)
{
return address(roleManager);
}
function getTokemManagerAddress() public view returns(address)
{
return address(tokenManager);
}
//after an authority is voted in it has the right to create at most one token for itself
function createNewToken(string memory description) public onlyAuthorities
{
tokenManager.createNewToken(msg.sender, description);
}
//ReservationSection
//Checks if object can be reservated by anyone right now, true is it can get reservated
function getIsReservable(uint256 id) public view returns (bool)
{
if(tripArray[indexOfID[id]].reserved == false) //Even when the users status gets changed from reserved to started after starting a trip, the trip status actually is reserved and started at the same time
return true;
if(block.number - tripArray[indexOfID[id]].reservedBlockNumber > tripArray[indexOfID[id]].maxReservedAmount && tripArray[indexOfID[id]].started == 0) //if a trip exceeds the maxReservedAmount but was not started yet it can be reserved by another party again
return true;
return false;
}
//Object needs to be free, user needs to be verifired and cant have other reservations
function reserveTrip(uint256 id) public onlyVerifiedRenter( tripArray[indexOfID[id]].objectType) onlyWithoutDebt isNotBlockedRenter
{
require(usermap[msg.sender].reserved == false);
//***************else: emit already reserved Trip event***************
require(getIsReservable(id) == true);
//***************else: emit already reserved by somone else event ***************
// require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20*****************
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //with 5secs blocktime around 4 mins worth of balance
usermap[msg.sender].reserved = true;
tripArray[indexOfID[id]].reserved = true;
tripArray[indexOfID[id]].renter = msg.sender;
tripArray[indexOfID[id]].reservedBlockNumber = block.number; //reservation gets timstampt as its validity is time limited
//***************emit Reservation successful event***************
// tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //give allowance instead?
}
//canceling trip is only possible if user reserved the trip but did not start it yet
function cancelReserve(uint256 id) public
{
if(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0)
{
tripArray[indexOfID[id]].reserved = false;
usermap[msg.sender].reserved = false;
//***************emit Reservation cancel successful event***************
// tokenManager.unblockOtherPaymentsOfUser(msg.sender);
}
//***************emit Reservation cancel not successful event***************
}
//start and end Trip section
//users can only start trips if they are not blocked, dont have any debt, have a minimum balancethreshold right now, have not started another trip yet, have given the tokenManager contract allowance to deduct tokens on their behalf
function startTrip(uint256 id) public onlyWithoutDebt isNotBlockedRenter
{
require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0);
require(usermap[msg.sender].started == false); //user can only have 1 started trip
// require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20*****************
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //user should have atleast enough balance for 50*5seconds -> around 4mins, minimum trip length
require(tokenManager.getHasTotalAllowance(msg.sender) == true);
//emit tripStart(tripAddress, tripKey, msg.sender, block.number);
tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //user gets blocked to make transactions to other addresses
tripArray[indexOfID[id]].readyToUse = false; //setting unlocked to false to esnure rental object is ready to use before user is charged
tripArray[indexOfID[id]].started = block.number;
usermap[msg.sender].started = true;
usermap[msg.sender].hasReportRight[tripArray[indexOfID[id]].lessor] = true; //renter gets the right to submit a report if something is wrong at the start or during the trip (e.g. object not found, object not functioning properly, lessor maliciously rejected end of trip), reports always have to be accompanied by off chain prove client side and will be reviewed by authorites (or possibly additional roles)
}
//Authority needs to confirm after start trip that device is ready to used (unlocked,...)
function confirmReadyToUse(uint256 id) public
{
require(tripArray[indexOfID[id]].lessor == msg.sender);
tripArray[indexOfID[id]].started = block.number; //update started so user does not pay for waiting time
tripArray[indexOfID[id]].readyToUse = true;
//emit unlocked event
}
//only callable by Renter, demanding End of trip has to be confrimed by the lessor (valid drop off location,...)
function demandEndTrip(uint256 id) public
{
require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0);
require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check
require(tripArray[indexOfID[id]].userDemandsEnd == 0);
tripArray[indexOfID[id]].userDemandsEnd = block.number;
}
//only callable by Renter, if lessor does not respond within 15 seconds, the renter can force end the trip
function userForcesEndTrip(uint256 id) public
{
require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0);
require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check
require(block.number > tripArray[indexOfID[id]].userDemandsEnd+3); //authority has 3 blocks time to answer to endDemand request
contractEndsTrip(id);
}
//only callable by lessor if user wants to end the trip, confirms that the pbject was returned adequatly
function confirmEndTrip(uint256 id) public
{
require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0);
require(tripArray[indexOfID[id]].userDemandsEnd != 0);
contractEndsTrip(id);
}
//only callable by lessor if user wants to end the trip, states that the pbject was returned inadequatly, rejects endTrip attempt of renter, renter can always report against malicious use of this function
function rejectEndTrip(uint256 id) public
{
require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0);
require(tripArray[indexOfID[id]].userDemandsEnd != 0);
tripArray[indexOfID[id]].userDemandsEnd = 0;
tripArray[indexOfID[id]].userDemandsEnd = 0;
//probably best to add an event and parse a string reason in parameters to state and explain why trip end was rejected
}
//On long rentals Lessor can call this function to ensure sufficient balance from the user -> maybe dont use that function, just tell the user and add debt -> good idea for charging station as renter can force end easily here
function doubtBalanceEnd(uint256 id) public
{
require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0);
//**************ERC20*********** if balance is not sufficient, renter can end contract
require(tripArray[indexOfID[id]].objectType == 4); //assuming object type 4 means charging station, function only makes sense for charging station
require(tokenManager.getTotalBalanceOfUser(msg.sender) > 10*tripArray[indexOfID[id]].price); //if user has less than 50seconds worth of balance then the Lessor can forceEnd the trip to prevent failure of payment
contractEndsTrip(id);
//Alternative: automatically end trips after certain amount and require user to rebook trips
}
//if renter demands end of trip and forces it or lessor confirms, the PlatformContract calls this function to handle payment and set all trip and user states to the right value again
function contractEndsTrip (uint256 id) internal
{
//*****************************ERC20Payment, out of money(?)**************************************
if(tripArray[indexOfID[id]].readyToUse) //user only needs to pay if the device actually responded and is ready to use -> maybe take out for testing to not require vehicle response all the time
{
if( tripArray[indexOfID[id]].userDemandsEnd == 0) //in this case user has to pay the difference form the current block number, should only happen if trip was force ended by authority
tokenManager.handlePayment(block.number - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,Β΄price of trip, from and to address
else //in this case user only has to be the time until he/she demanded end of trip (user does not have to pay for the time it takes the rental object authority to confirm the trip)
tokenManager.handlePayment(tripArray[indexOfID[id]].userDemandsEnd - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,Β΄price of trip, from and to address
}
if(tokenManager.hasDebt(msg.sender) == 0)
tokenManager.unblockOtherPaymentsOfUser(msg.sender); //only unblocks user if the user managed to pay the full amount
usermap[msg.sender].started = false;
usermap[msg.sender].hasRatingRight[tripArray[indexOfID[id]].lessor] = true;
//address def;
tripArray[indexOfID[id]].renter = address(0); //-> prob adress(0)
tripArray[indexOfID[id]].reserved = false;
tripArray[indexOfID[id]].started = 0;
tripArray[indexOfID[id]].userDemandsEnd = 0;
tripArray[indexOfID[id]].readyToUse = false; //restrict user from access to the vehicle => needs to be replicated in device logic
}
//returns the maxiumum amount of blocks the user can still rent the device before he/she runs out of balance, useful for client side warnings
function getMaxRamainingTime(uint256 id) public view returns (uint256)
{
require(tripArray[indexOfID[id]].started != 0);
uint256 currentPrice = (block.number - tripArray[indexOfID[id]].started)*tripArray[indexOfID[id]].price;
uint256 userBalance = tokenManager.getTotalBalanceOfUser(tripArray[indexOfID[id]].renter);
uint256 theoreticalBalanceLeft = currentPrice -userBalance;
return theoreticalBalanceLeft/tripArray[indexOfID[id]].price;
}
//User has a rating right for each ended trip
function rateTrip(address LessorAddress, uint8 rating) public
{
require(usermap[msg.sender].hasRatingRight[LessorAddress] == true);
require(rating > 0);
require(rating < 6);
usermap[LessorAddress].rating += rating;
usermap[LessorAddress].ratingCount++;
usermap[msg.sender].hasRatingRight[LessorAddress] = false;
}
//User has the right to report a lessor for each started trip (might be useful to also add one for each reserved trip but allows spamming)
function reportLessor(address LessorAddress, uint8 rating, string memory message) public
{
require(usermap[msg.sender].hasReportRight[LessorAddress] == true);
//****here reports could be stored in an array with an own report governance logic or emited as an event for offchain handling by auhtorities which then return for on chain punishment****
usermap[msg.sender].hasReportRight[LessorAddress] = false;
}
//Offer trip section
//use DateTime contract before to convert desired Date to uint epoch
function offerTrip(uint256 startTime, uint256 endTime, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedLessor(objectType) isNotBlockedLessor
{
offer memory tempOffer;
tempOffer.startTime = startTime;
tempOffer.endTime = endTime;
tempOffer.latpickupLocation = latpickupLocation;
tempOffer.longpickupLocation = longpickupLocation;
tempOffer.lessor = msg.sender;
tempOffer.price = price;
tempOffer.latPolygons = latPolygons;
tempOffer.longPolygons = longPolygons;
tempOffer.maxReservedAmount = maxReservedAmount;
tempOffer.objectType = objectType;
tempOffer.model = model;
tempOffer.id = indexOfID.length; // set id to the next following
tripArray.push(tempOffer); //add trip to the tripArray
indexOfID.push(tripArray.length-1); //save location for latest id -> is linked to tempOffer.id from before
}
//Change Trip details Section
//lessors can update object location if not in use or reserved
function updateObjectLocation(uint256 id, uint64 newlat, uint64 newlong) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary
{
require(tripArray[indexOfID[id]].lessor == msg.sender);
require(tripArray[indexOfID[id]].reserved == false);
tripArray[indexOfID[id]].longpickupLocation = newlong;
tripArray[indexOfID[id]].latpickupLocation = newlat;
}
//lessors can update object price if not in use or reserved
function updateObjectPrice(uint256 id, uint256 price) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary -> check already happened before
{
require(tripArray[indexOfID[id]].lessor == msg.sender);
require(tripArray[indexOfID[id]].reserved == false);
tripArray[indexOfID[id]].price = price;
}
//lessors can delete their offers if not in use or reserved
function deleteTrip(uint256 id) public
{
require(tripArray[indexOfID[id]].reserved == false);
require(tripArray[indexOfID[id]].lessor == msg.sender); //trip can only be deleted if not reserved (coveres reserved and started) and if the function is called by the Lessor
tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element
indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to
delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved
indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted
tripArray.length--; //reduce length of array by one
}
//maybe restrict function to authorities as its a costly operation, deletes outdated trips from the platform (trips with expired latest return date), frees storage
function deleteOutdatedTrips() public
{
for(uint256 i = 1; i < tripArray.length; i++) //beginning at 1 since 0 trip is not used
{
if(tripArray[i].endTime < block.timestamp)
deleteTripInternal(i);
}
}
//difference from above: Lessor does not have to be msg.sender, gets called by the PlatformContract to delete outdated Trips
function deleteTripInternal(uint256 id) internal
{
require(tripArray[indexOfID[id]].reserved == false); //object can only be rented if not in use
tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element
indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to
delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved
indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted
tripArray.length--; //reduce length of array by one
}
//Get Trip Information Section
function getTrip(uint256 id) public view returns(offer memory) //offer[] memory
{
return tripArray[indexOfID[id]]; //maybe mapindex has to be set to allow client to refind the trip -> probably better to set this client side when looping
}
function getLength() public view returns (uint256) //returns total amount of current trips
{
return tripArray.length;
}
//index +1 to make 0 distinguishable -no item found
function getTripID(uint256 index) public view returns(uint256)
{
return tripArray[index].id;
}
//get sum of ratings and amount of ratings, need to be divided client side to retrive actual average rating -> costly operation
function getRating(address a) public view returns( uint256[2] memory)
{
uint256[2] memory ratingArray;
ratingArray[0] = usermap[a].rating;
ratingArray[1] = usermap[a].ratingCount;
return ratingArray;
}
/**
function testGetTokenBalance(bool option) public view returns (uint256)
{
if(option == false)
{
return authorityTokens[msg.sender].totalSupply();
}
else{
address def;
return authorityTokens[def].totalSupply();
}
}
*/
}
| objectType descirbes the sharing object category (car, charging station, bike, ...) | modifier onlyVerifiedLessor(uint8 objectType) {
require (roleManager.isVerifiedLessor(msg.sender, objectType) == true);
_;
}
modifier onlyVerifiers()
| 5,489,669 | [
1,
1612,
559,
3044,
481,
70,
281,
326,
21001,
733,
3150,
261,
9815,
16,
1149,
1998,
13282,
16,
324,
2547,
16,
1372,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
24369,
15313,
280,
12,
11890,
28,
16400,
13,
288,
203,
3639,
2583,
261,
4615,
1318,
18,
291,
24369,
15313,
280,
12,
3576,
18,
15330,
16,
16400,
13,
422,
638,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
1377,
203,
1377,
203,
1377,
9606,
1338,
3945,
3383,
1435,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-03
*/
/**
*Submitted for verification at Etherscan.io on 2022-02-22
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
// File @openzeppelin/contracts/utils/[emailΒ protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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]
/**
* @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/introspection/[emailΒ protected]
/**
* @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]
/**
* @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 whiteed 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 whiteed 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]
/**
* @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]
/**
* @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]
/**
* @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]
/**
* @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]
/**
* @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]
/**
* @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 whiteed 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]
/**
* @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]
/**
* @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 whites 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/utils/math/[emailΒ protected]
// 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;
}
}
}
/**
* @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).
*/
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 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// 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) private _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;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @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 = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
if (tokenCount == 0)
{
return tokenIds;
}
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx] = i;
tokenIdsIdx++;
if (tokenIdsIdx == tokenCount) {
return tokenIds;
}
}
}
revert("ERC721A: unable to get walletOfOwner");
}
/**
* @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);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; 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 virtual 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 Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
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);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, 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] = TokenOwnership(
prevOwnership.addr,
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);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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 SLIMYS is ERC721A, Ownable {
constructor() ERC721A("SLIMYS", "S",20) {}
using SafeMath for uint256;
using Strings for uint256;
string private baseURI;
string private blindURI;
uint256 public constant BUY_LIMIT_PER_TX = 20;
uint256 public MAX_NFT_PUBLIC = 4444;
uint256 private constant MAX_NFT = 4444;
uint256 public NFTPrice = 190000000000000000; // 0.19 ETH
uint256 public NFTPriceBundle = 360000000000000000; // 0.36 ETH
bool public reveal;
bool public isActive;
bool public isPresaleActive;
bool public freeMintActive;
bytes32 public root;
uint256 public WHITELIST_MAX_MINT = 2;
mapping(address => uint256) public whiteListClaimed;
mapping(address => bool) private giveawayMintClaimed;
/*
* Function to reveal all Slimmies
*/
function revealNow()
external
onlyOwner
{
reveal = true;
}
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function setPresaleActive to activate/desactivate the whitelist/raffle presale
*/
function setPresaleActive(
bool _isActive
)
external
onlyOwner
{
isPresaleActive = _isActive;
}
/*
* Function setFreeMintActive to activate/desactivate the free mint capability
*/
function setFreeMintActive(
bool _isActive
)
external
onlyOwner
{
freeMintActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
/*
* Function to set NFT Price
*/
function setNFTPrice(uint256 _price) external onlyOwner {
NFTPrice = _price;
}
/*
* Function to set Max NFT
*/
function setNFTmax(uint256 max) external onlyOwner {
MAX_NFT_PUBLIC = max;
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
address[11] memory _team = [
0xc224301674c3fca16383f5D1F36A08e7048e4d1C,
0xe70bB226F09399407C6e59a058BEAF34e785BB75, //50% until X NFT sold
0x88132cD837e8E952Cc38c6f71E6969C6E83D1Ffb, //50% until X NFT sold
0xC89E9ecF1B2900656ECba77E1Da89600f187A50D,
0xBC3F581C6B540447D61a788B4547C66A45584097,
0x5Bca3d2c54f7cEAB7f0b8e3b05Adf46B016823fD,
0x23C625789c391463997267BDD8b21e5E266014F6,
0x73b4953783087AfB8674a7a7eB082c3DEB31aFF5,
0x4335d2Bf93309701065961e359eEd999eD2B1Ea9,
0xCeC07E954f81224414Ac0a79249fd64577a0B727,
0x6a4AE2E404d7D2EB663079b449b2Cf497c97335F
];
uint32[11] memory _teamShares = [
uint32(485),
uint32(160),
uint32(160),
uint32(30),
uint32(10),
uint32(10),
uint32(15),
uint32(10),
uint32(30),
uint32(50),
uint32(40)
];
for(uint256 i = 0; i < _team.length; i++){
payable(_team[i]).transfer((balance * _teamShares[i]) / 1000);
}
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdrawTo(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
payable(_to).transfer(balance);
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Presale is still active');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
_safeMint(msg.sender, _numOfTokens);
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint256 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Sale is not active');
require(isPresaleActive, 'Whitelist is not active');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
if (!freeMintActive){
require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
if(_numOfTokens==2){
require(NFTPriceBundle == msg.value, "Ether value sent is not correct");
}else{
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
}
whiteListClaimed[msg.sender] += _numOfTokens;
_safeMint(msg.sender, _numOfTokens);
} else {
require(totalSupply() <= MAX_NFT, 'All tokens have been minted');
require(_numOfTokens == 1, 'Cannot purchase this many tokens');
require(!giveawayMintClaimed[msg.sender], 'Already claimed giveaway');
giveawayMintClaimed[msg.sender] = true;
_safeMint(msg.sender, _numOfTokens);
}
}
/*
* Function to mint NFTs for giveaway and partnerships
*/
function mintByOwner(
address _to,
uint256 _num
)
public
onlyOwner
{
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, _num);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintMultipleByOwner(
address[] memory _to,
uint256 _num
)
public
onlyOwner
{
for(uint256 i = 0; i < _to.length; i++){
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], _num);
}
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function tokenURI(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
// Set Root for whitelist and raffle to participate in presale
function setRootAndMax(uint256 _root,uint256 _max) onlyOwner() public {
root = bytes32(_root);
WHITELIST_MAX_MINT = _max;
}
// Verify MerkleProof
function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
} | * @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 {
pragma solidity ^0.8.12;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 10,946,238 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1772,
288,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2138,
31,
203,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
interface CommonWallet {
function receive() external payable;
}
library StringUtils {
function concat(string _a, string _b)
internal
pure
returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
library UintStringUtils {
function toString(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);
}
}
// @title AddressUtils
// @dev Utility library of inline functions on addresses
library AddressUtils {
// Returns whether the target address is a contract
// @dev This function will return false if invoked during the constructor of a contract,
// as the code is not actually created until after the constructor finishes.
// @param addr address to check
// @return whether the target address is a contract
function isContract(address addr)
internal
view
returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// @title SafeMath256
// @dev Math operations with safety checks that throw on error
library SafeMath256 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
// @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath32 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath8 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint8 a, uint8 b) internal pure returns (uint8 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
// @dev Integer division of two numbers, truncating the quotient.
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint8 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(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/// @title A facet of DragonCore that manages special access privileges.
contract DragonAccessControl
{
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Contract owner
address internal controller_;
/// @dev Contract modes
enum Mode {TEST, PRESALE, OPERATE}
/// @dev Contract state
Mode internal mode_ = Mode.TEST;
/// @dev OffChain Server accounts ('minions') addresses
/// It's used for money withdrawal and export of tokens
mapping(address => bool) internal minions_;
/// @dev Presale contract address. Can call `presale` method.
address internal presale_;
// Modifiers ---------------------------------------------------------------
/// @dev Limit execution to controller account only.
modifier controllerOnly() {
require(controller_ == msg.sender, "controller_only");
_;
}
/// @dev Limit execution to minion account only.
modifier minionOnly() {
require(minions_[msg.sender], "minion_only");
_;
}
/// @dev Limit execution to test time only.
modifier testModeOnly {
require(mode_ == Mode.TEST, "test_mode_only");
_;
}
/// @dev Limit execution to presale time only.
modifier presaleModeOnly {
require(mode_ == Mode.PRESALE, "presale_mode_only");
_;
}
/// @dev Limit execution to operate time only.
modifier operateModeOnly {
require(mode_ == Mode.OPERATE, "operate_mode_only");
_;
}
/// @dev Limit execution to presale account only.
modifier presaleOnly() {
require(msg.sender == presale_, "presale_only");
_;
}
/// @dev set state to Mode.OPERATE.
function setOperateMode()
external
controllerOnly
presaleModeOnly
{
mode_ = Mode.OPERATE;
}
/// @dev Set presale contract address. Becomes useless when presale is over.
/// @param _presale Presale contract address.
function setPresale(address _presale)
external
controllerOnly
{
presale_ = _presale;
}
/// @dev set state to Mode.PRESALE.
function setPresaleMode()
external
controllerOnly
testModeOnly
{
mode_ = Mode.PRESALE;
}
/// @dev Get controller address.
/// @return Address of contract's controller.
function controller()
external
view
returns(address)
{
return controller_;
}
/// @dev Transfer control to new address. Set controller an approvee for
/// tokens that managed by contract itself. Remove previous controller value
/// from contract's approvees.
/// @param _to New controller address.
function setController(address _to)
external
controllerOnly
{
require(_to != NA, "_to");
require(controller_ != _to, "already_controller");
controller_ = _to;
}
/// @dev Check if address is a minion.
/// @param _addr Address to check.
/// @return True if address is a minion.
function isMinion(address _addr)
public view returns(bool)
{
return minions_[_addr];
}
function getCurrentMode()
public view returns (Mode)
{
return mode_;
}
}
/// @dev token description, storage and transfer functions
contract DragonBase is DragonAccessControl
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using StringUtils for string;
using UintStringUtils for uint;
/// @dev The Birth event is fired whenever a new dragon comes into existence.
event Birth(address owner, uint256 petId, uint256 tokenId, uint256 parentA, uint256 parentB, string genes, string params);
/// @dev Token name
string internal name_;
/// @dev Token symbol
string internal symbol_;
/// @dev Token resolving url
string internal url_;
struct DragonToken {
// Constant Token params
uint8 genNum; // generation number. uses for dragon view
string genome; // genome description
uint256 petId; // offchain dragon identifier
// Parents
uint256 parentA;
uint256 parentB;
// Game-depening Token params
string params; // can change in export operation
// State
address owner;
}
/// @dev Count of minted tokens
uint256 internal mintCount_;
/// @dev Maximum token supply
uint256 internal maxSupply_;
/// @dev Count of burn tokens
uint256 internal burnCount_;
// Tokens state
/// @dev Token approvals values
mapping(uint256 => address) internal approvals_;
/// @dev Operator approvals
mapping(address => mapping(address => bool)) internal operatorApprovals_;
/// @dev Index of token in owner's token list
mapping(uint256 => uint256) internal ownerIndex_;
/// @dev Owner's tokens list
mapping(address => uint256[]) internal ownTokens_;
/// @dev Tokens
mapping(uint256 => DragonToken) internal tokens_;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Add token to new owner. Increase owner's balance.
/// @param _to Token receiver.
/// @param _tokenId New token id.
function _addTo(address _to, uint256 _tokenId)
internal
{
DragonToken storage token = tokens_[_tokenId];
require(token.owner == NA, "taken");
uint256 lastIndex = ownTokens_[_to].length;
ownTokens_[_to].push(_tokenId);
ownerIndex_[_tokenId] = lastIndex;
token.owner = _to;
}
/// @dev Create new token and increase mintCount.
/// @param _genome New token's genome.
/// @param _params Token params string.
/// @param _parentA Token A parent.
/// @param _parentB Token B parent.
/// @return New token id.
function _createToken(
address _to,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId,
string _params
)
internal returns(uint256)
{
uint256 tokenId = mintCount_.add(1);
mintCount_ = tokenId;
DragonToken memory token = DragonToken(
_genNum,
_genome,
_petId,
_parentA,
_parentB,
_params,
NA
);
tokens_[tokenId] = token;
_addTo(_to, tokenId);
emit Birth(_to, _petId, tokenId, _parentA, _parentB, _genome, _params);
return tokenId;
}
/// @dev Get token genome.
/// @param _tokenId Token id.
/// @return Token's genome.
function getGenome(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].genome;
}
/// @dev Get token params.
/// @param _tokenId Token id.
/// @return Token's params.
function getParams(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].params;
}
/// @dev Get token parentA.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentA(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentA;
}
/// @dev Get token parentB.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentB(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentB;
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function isExisting(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Receive maxium token supply value.
/// @return Contracts `maxSupply_` variable.
function maxSupply()
external view returns(uint256)
{
return maxSupply_;
}
/// @dev Set url prefix for tokenURI generation.
/// @param _url Url prefix value.
function setUrl(string _url)
external controllerOnly
{
url_ = _url;
}
/// @dev Get token symbol.
/// @return Token symbol name.
function symbol()
external view returns(string)
{
return symbol_;
}
/// @dev Get token URI to receive offchain information by it's id.
/// @param _tokenId Token id.
/// @return URL string. For example "http://erc721.tld/tokens/1".
function tokenURI(uint256 _tokenId)
external view returns(string)
{
return url_.concat(_tokenId.toString());
}
/// @dev Get token name.
/// @return Token name string.
function name()
external view returns(string)
{
return name_;
}
/// @dev return information about _owner tokens
function getTokens(address _owner)
external view returns (uint256[], uint256[], byte[])
{
uint256[] memory tokens = ownTokens_[_owner];
uint256[] memory tokenIds = new uint256[](tokens.length);
uint256[] memory petIds = new uint256[](tokens.length);
byte[] memory genomes = new byte[](tokens.length * 77);
uint index = 0;
for(uint i = 0; i < tokens.length; i++) {
uint256 tokenId = tokens[i];
DragonToken storage token = tokens_[tokenId];
tokenIds[i] = tokenId;
petIds[i] = token.petId;
bytes storage genome = bytes(token.genome);
for(uint j = 0; j < genome.length; j++) {
genomes[index++] = genome[j];
}
}
return (tokenIds, petIds, genomes);
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @dev See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721.sol
contract ERC721Basic
{
/// @dev Emitted when token approvee is set
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev Emitted when owner approve all own tokens to operator.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev Emitted when user deposit some funds.
event Deposit(address indexed _sender, uint256 _value);
/// @dev Emitted when user deposit some funds.
event Withdraw(address indexed _sender, uint256 _value);
/// @dev Emitted when token transferred to new owner
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Required methods
function balanceOf(address _owner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function getApproved(uint256 _tokenId) public view returns (address _to);
//function transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic
{
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver
{
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data )
public returns(bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Metadata, ERC721Receiver
{
/// @dev Interface signature 721 for interface detection.
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
}
/// @dev ERC721 methods
contract DragonOwnership is ERC721, DragonBase
{
using StringUtils for string;
using UintStringUtils for uint;
using AddressUtils for address;
/// @dev Emitted when token transferred to new owner. Additional fields is petId, genes, params
/// it uses for client-side indication
event TransferInfo(address indexed _from, address indexed _to, uint256 _tokenId, uint256 petId, string genes, string params);
/// @dev Specify if _addr is token owner or approvee. Also check if `_addr`
/// is operator for token owner.
/// @param _tokenId Token to check ownership of.
/// @param _addr Address to check if it's an owner or an aprovee of `_tokenId`.
/// @return True if token can be managed by provided `_addr`.
function isOwnerOrApproved(uint256 _tokenId, address _addr)
public view returns(bool)
{
DragonToken memory token = tokens_[_tokenId];
if (token.owner == _addr) {
return true;
}
else if (isApprovedFor(_tokenId, _addr)) {
return true;
}
else if (isApprovedForAll(token.owner, _addr)) {
return true;
}
return false;
}
/// @dev Limit execution to token owner or approvee only.
/// @param _tokenId Token to check ownership of.
modifier ownerOrApprovedOnly(uint256 _tokenId) {
require(isOwnerOrApproved(_tokenId, msg.sender), "tokenOwnerOrApproved_only");
_;
}
/// @dev Contract's own token only acceptable.
/// @param _tokenId Contract's token id.
modifier ownOnly(uint256 _tokenId) {
require(tokens_[_tokenId].owner == address(this), "own_only");
_;
}
/// @dev Determine if token is approved for specified approvee.
/// @param _tokenId Target token id.
/// @param _approvee Approvee address.
/// @return True if so.
function isApprovedFor(uint256 _tokenId, address _approvee)
public view returns(bool)
{
return approvals_[_tokenId] == _approvee;
}
/// @dev Specify is given address set as operator with setApprovalForAll.
/// @param _owner Token owner.
/// @param _operator Address to check if it an operator.
/// @return True if operator is set.
function isApprovedForAll(address _owner, address _operator)
public view returns(bool)
{
return operatorApprovals_[_owner][_operator];
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function exists(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Get owner of a token.
/// @param _tokenId Token owner id.
/// @return Token owner address.
function ownerOf(uint256 _tokenId)
public view returns(address)
{
return tokens_[_tokenId].owner;
}
/// @dev Get approvee address. If there is not approvee returns 0x0.
/// @param _tokenId Token id to get approvee of.
/// @return Approvee address or 0x0.
function getApproved(uint256 _tokenId)
public view returns(address)
{
return approvals_[_tokenId];
}
/// @dev Grant owner alike controll permissions to third party.
/// @param _to Permission receiver.
/// @param _tokenId Granted token id.
function approve(address _to, uint256 _tokenId)
external ownerOrApprovedOnly(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != NA || _to != NA) {
approvals_[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/// @dev Current total tokens supply. Always less then maxSupply.
/// @return Difference between minted and burned tokens.
function totalSupply()
public view returns(uint256)
{
return mintCount_;
}
/// @dev Get number of tokens which `_owner` owns.
/// @param _owner Address to count own tokens.
/// @return Count of owned tokens.
function balanceOf(address _owner)
external view returns(uint256)
{
return ownTokens_[_owner].length;
}
/// @dev Internal set approval for all without _owner check.
/// @param _owner Granting user.
/// @param _to New account approvee.
/// @param _approved Set new approvee status.
function _setApprovalForAll(address _owner, address _to, bool _approved)
internal
{
operatorApprovals_[_owner][_to] = _approved;
emit ApprovalForAll(_owner, _to, _approved);
}
/// @dev Set approval for all account tokens.
/// @param _to Approvee address.
/// @param _approved Value true or false.
function setApprovalForAll(address _to, bool _approved)
external
{
require(_to != msg.sender);
_setApprovalForAll(msg.sender, _to, _approved);
}
/// @dev Remove approval bindings for token. Do nothing if no approval
/// exists.
/// @param _from Address of token owner.
/// @param _tokenId Target token id.
function _clearApproval(address _from, uint256 _tokenId)
internal
{
if (approvals_[_tokenId] == NA) {
return;
}
approvals_[_tokenId] = NA;
emit Approval(_from, NA, _tokenId);
}
/// @dev Check if contract was received by other side properly if receiver
/// is a ctontract.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
/// @return True on success.
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal returns(bool)
{
if (! _to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
/// @dev Remove token from owner. Unrecoverable.
/// @param _tokenId Removing token id.
function _remove(uint256 _tokenId)
internal
{
address owner = tokens_[_tokenId].owner;
_removeFrom(owner, _tokenId);
}
/// @dev Completely remove token from the contract. Unrecoverable.
/// @param _owner Owner of removing token.
/// @param _tokenId Removing token id.
function _removeFrom(address _owner, uint256 _tokenId)
internal
{
uint256 lastIndex = ownTokens_[_owner].length.sub(1);
uint256 lastToken = ownTokens_[_owner][lastIndex];
// Swap users token
ownTokens_[_owner][ownerIndex_[_tokenId]] = lastToken;
ownTokens_[_owner].length--;
// Swap token indexes
ownerIndex_[lastToken] = ownerIndex_[_tokenId];
ownerIndex_[_tokenId] = 0;
DragonToken storage token = tokens_[_tokenId];
token.owner = NA;
}
/// @dev Transfer token from owner `_from` to another address or contract
/// `_to` by it's `_tokenId`.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function transferFrom( address _from, address _to, uint256 _tokenId )
public ownerOrApprovedOnly(_tokenId)
{
require(_from != NA);
require(_to != NA);
_clearApproval(_from, _tokenId);
_removeFrom(_from, _tokenId);
_addTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
DragonToken storage token = tokens_[_tokenId];
emit TransferInfo(_from, _to, _tokenId, token.petId, token.genome, token.params);
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params
)
public
{
updateAndSafeTransferFrom(_to, _tokenId, _params, "");
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token and send
/// protion of _data to it.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
/// @param _data Notification data.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params,
bytes _data
)
public
{
// Safe transfer from
updateAndTransferFrom(_to, _tokenId, _params, 0, 0);
require(_checkAndCallSafeTransfer(address(this), _to, _tokenId, _data));
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndTransferFrom(
address _to,
uint256 _tokenId,
string _params,
uint256 _petId,
uint256 _transferCost
)
public
ownOnly(_tokenId)
minionOnly
{
require(bytes(_params).length > 0, "params_length");
// Update
tokens_[_tokenId].params = _params;
if (tokens_[_tokenId].petId == 0 ) {
tokens_[_tokenId].petId = _petId;
}
address from = tokens_[_tokenId].owner;
// Transfer from
transferFrom(from, _to, _tokenId);
// send to the server's wallet the transaction cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/// @dev Burn owned token. Increases `burnCount_` and decrease `totalSupply`
/// value.
/// @param _tokenId Id of burning token.
function burn(uint256 _tokenId)
public
ownerOrApprovedOnly(_tokenId)
{
address owner = tokens_[_tokenId].owner;
_remove(_tokenId);
burnCount_ += 1;
emit Transfer(owner, NA, _tokenId);
}
/// @dev Receive count of burned tokens. Should be greater than `totalSupply`
/// but less than `mintCount`.
/// @return Number of burned tokens
function burnCount()
external
view
returns(uint256)
{
return burnCount_;
}
function onERC721Received(address, uint256, bytes)
public returns(bytes4)
{
return ERC721_RECEIVED;
}
}
/// @title Managing contract. implements the logic of buying tokens, depositing / withdrawing funds
/// to the project account and importing / exporting tokens
contract EtherDragonsCore is DragonOwnership
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using AddressUtils for address;
using StringUtils for string;
using UintStringUtils for uint;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Bounty tokens count limit
uint256 public constant BOUNTY_LIMIT = 2500;
/// @dev Presale tokens count limit
uint256 public constant PRESALE_LIMIT = 7500;
///@dev Total gen0tokens generation limit
uint256 public constant GEN0_CREATION_LIMIT = 90000;
/// @dev Number of tokens minted in presale stage
uint256 internal presaleCount_;
/// @dev Number of tokens minted for bounty campaign
uint256 internal bountyCount_;
///@dev Company bank address
address internal bank_;
// Extension ---------------------------------------------------------------
/// @dev Contract is not payable. To fullfil balance method `depositTo`
/// should be used.
function ()
public payable
{
revert();
}
/// @dev amount on the account of the contract. This amount consists of deposits from players and the system reserve for payment of transactions
/// the player at any time to withdraw the amount corresponding to his account in the game, minus the cost of the transaction
function getBalance()
public view returns (uint256)
{
return address(this).balance;
}
/// @dev at the moment of creation of the contract we transfer the address of the bank
/// presell contract address set later
constructor(
address _bank
)
public
{
require(_bank != NA);
controller_ = msg.sender;
bank_ = _bank;
// Meta
name_ = "EtherDragons";
symbol_ = "ED";
url_ = "https://game.etherdragons.world/token/";
// Token mint limit
maxSupply_ = GEN0_CREATION_LIMIT + BOUNTY_LIMIT + PRESALE_LIMIT;
}
/// Number of tokens minted in presale stage
function totalPresaleCount()
public view returns(uint256)
{
return presaleCount_;
}
/// @dev Number of tokens minted for bounty campaign
function totalBountyCount()
public view returns(uint256)
{
return bountyCount_;
}
/// @dev Check if new token could be minted. Return true if count of minted
/// tokens less than could be minted through contract deploy.
/// Also, tokens can not be created more often than once in mintDelay_ minutes
/// @return True if current count is less then maximum tokens available for now.
function canMint()
public view returns(bool)
{
return (mintCount_ + presaleCount_ + bountyCount_) < maxSupply_;
}
/// @dev Here we write the addresses of the wallets of the server from which it is accessed
/// to contract methods.
/// @param _to New minion address
function minionAdd(address _to)
external controllerOnly
{
require(minions_[_to] == false, "already_minion");
// ΡΠ°Π·ΡΠ΅ΡΠ°Π΅ΠΌ ΡΡΠΎΠΌΡ Π°Π΄ΡΠ΅ΡΡ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡΡΡ ΡΠΎΠΊΠ΅Π½Π°ΠΌΠΈ ΠΊΠΎΠ½ΡΠ°ΠΊΡΠ°
// allow the address to use contract tokens
_setApprovalForAll(address(this), _to, true);
minions_[_to] = true;
}
/// @dev delete the address of the server wallet
/// @param _to Minion address
function minionRemove(address _to)
external controllerOnly
{
require(minions_[_to], "not_a_minion");
// and forbid this wallet to use tokens of the contract
_setApprovalForAll(address(this), _to, false);
minions_[_to] = false;
}
/// @dev Here the player can put funds to the account of the contract
/// and get the same amount of in-game currency
/// the game server understands who puts money at the wallet address
function depositTo()
public payable
{
emit Deposit(msg.sender, msg.value);
}
/// @dev Transfer amount of Ethers to specified receiver. Only owner can
// call this method.
/// @param _to Transfer receiver.
/// @param _amount Transfer value.
/// @param _transferCost Transfer cost.
function transferAmount(address _to, uint256 _amount, uint256 _transferCost)
external minionOnly
{
require((_amount + _transferCost) <= address(this).balance, "not enough money!");
_to.transfer(_amount);
// send to the wallet of the server the transfer cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
emit Withdraw(_to, _amount);
}
/// @dev Mint new token with specified params. Transfer `_fee` to the
/// `bank`.
/// @param _to New token owner.
/// @param _fee Transaction fee.
/// @param _genNum Generation number..
/// @param _genome New genome unique value.
/// @param _parentA Parent A.
/// @param _parentB Parent B.
/// @param _petId Pet identifier.
/// @param _params List of parameters for pet.
/// @param _transferCost Transfer cost.
/// @return New token id.
function mintRelease(
address _to,
uint256 _fee,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId, //if petID = 0, then it was created outside of the server
string _params,
uint256 _transferCost
)
external minionOnly operateModeOnly returns(uint256)
{
require(canMint(), "can_mint");
require(_to != NA, "_to");
require((_fee + _transferCost) <= address(this).balance, "_fee");
require(bytes(_params).length != 0, "params_length");
require(bytes(_genome).length == 77, "genome_length");
// Parents should be both 0 or both not.
if (_parentA != 0 && _parentB != 0) {
require(_parentA != _parentB, "same_parent");
}
else if (_parentA == 0 && _parentB != 0) {
revert("parentA_empty");
}
else if (_parentB == 0 && _parentA != 0) {
revert("parentB_empty");
}
uint256 tokenId = _createToken(_to, _genNum, _genome, _parentA, _parentB, _petId, _params);
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
// Transfer mint fee to the fund
CommonWallet(bank_).receive.value(_fee)();
emit Transfer(NA, _to, tokenId);
// send to the server wallet server the transfer cost,
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
return tokenId;
}
/// @dev Create new token via presale state
/// @param _to New token owner.
/// @param _genome New genome unique value.
/// @return New token id.
/// at the pre-sale stage we sell the zero-generation pets, which have only a genome.
/// other attributes of such a token get when importing to the server
function mintPresell(address _to, string _genome)
external presaleOnly presaleModeOnly returns(uint256)
{
require(presaleCount_ < PRESALE_LIMIT, "presale_limit");
// Ρ ΠΏΡΠ΅ΡΠ΅ΠΉΠ» ΠΏΠ΅ΡΠ° Π½Π΅Ρ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΠΎΠ². ΠΡ
ΠΎΠ½ ΠΏΠΎΠ»ΡΡΠΈΡ ΠΏΠΎΡΠ»Π΅ Π²Π²ΠΎΠ΄Π° Π² ΠΈΠ³ΡΡ.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
presaleCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
/// @dev Create new token for bounty activity
/// @param _to New token owner.
/// @return New token id.
function mintBounty(address _to, string _genome)
external controllerOnly returns(uint256)
{
require(bountyCount_ < BOUNTY_LIMIT, "bounty_limit");
// bounty pet has no parameters. They will receive them after importing to the game.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
bountyCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
}
contract Presale
{
// Extension ---------------------------------------------------------------
using AddressUtils for address;
// Events ------------------------------------------------------------------
///the event is fired when starting a new wave presale stage
event StageBegin(uint8 stage, uint256 timestamp);
///the event is fired when token sold
event TokensBought(address buyerAddr, uint256[] tokenIds, bytes genomes);
// Types -------------------------------------------------------------------
struct Stage {
// Predefined values
uint256 price; // token's price on the stage
uint16 softcap; // stage softCap
uint16 hardcap; // stage hardCap
// Unknown values
uint16 bought; // sold on stage
uint32 startDate; // stage's beginDate
uint32 endDate; // stage's endDate
}
// Constants ---------------------------------------------------------------
// 10 stages of 5 genocodes
uint8 public constant STAGES = 10;
uint8 internal constant TOKENS_PER_STAGE = 5;
address constant NA = address(0);
// State -------------------------------------------------------------------
address internal CEOAddress; // contract owner
address internal bank_; // profit wallet address (not a contract)
address internal erc721_; // main contract address
/// @dev genomes for bounty stage
string[TOKENS_PER_STAGE][STAGES] internal genomes_;
/// stages data
Stage[STAGES] internal stages_;
// internal transaction counter, it uses for random generator
uint32 internal counter_;
/// stage is over
bool internal isOver_;
/// stage number
uint8 internal stageIndex_;
/// stage start Data
uint32 internal stageStart_;
// Lifetime ----------------------------------------------------------------
constructor(
address _bank,
address _erc721
)
public
{
require(_bank != NA, '_bank');
require(_erc721.isContract(), '_erc721');
CEOAddress = msg.sender;
// Addresses should not be the same.
require(_bank != CEOAddress, "bank = CEO");
require(CEOAddress != _erc721, "CEO = erc721");
require(_erc721 != _bank, "bank = erc721");
// Update state
bank_ = _bank;
erc721_ = _erc721;
// stages data
stages_[0].price = 10 finney;
stages_[0].softcap = 100;
stages_[0].hardcap = 300;
stages_[1].price = 20 finney;
stages_[1].softcap = 156;
stages_[1].hardcap = 400;
stages_[2].price = 32 finney;
stages_[2].softcap = 212;
stages_[2].hardcap = 500;
stages_[3].price = 45 finney;
stages_[3].softcap = 268;
stages_[3].hardcap = 600;
stages_[4].price = 58 finney;
stages_[4].softcap = 324;
stages_[4].hardcap = 700;
stages_[5].price = 73 finney;
stages_[5].softcap = 380;
stages_[5].hardcap = 800;
stages_[6].price = 87 finney;
stages_[6].softcap = 436;
stages_[6].hardcap = 900;
stages_[7].price = 102 finney;
stages_[7].softcap = 492;
stages_[7].hardcap = 1000;
stages_[8].price = 118 finney;
stages_[8].softcap = 548;
stages_[8].hardcap = 1100;
stages_[9].price = 129 finney;
stages_[9].softcap = 604;
stages_[9].hardcap = 1200;
}
/// fill the genomes data
function setStageGenomes(
uint8 _stage,
string _genome0,
string _genome1,
string _genome2,
string _genome3,
string _genome4
)
external controllerOnly
{
genomes_[_stage][0] = _genome0;
genomes_[_stage][1] = _genome1;
genomes_[_stage][2] = _genome2;
genomes_[_stage][3] = _genome3;
genomes_[_stage][4] = _genome4;
}
/// @dev Contract itself is non payable
function ()
public payable
{
revert();
}
// Modifiers ---------------------------------------------------------------
/// only from contract owner
modifier controllerOnly() {
require(msg.sender == CEOAddress, 'controller_only');
_;
}
/// only for active stage
modifier notOverOnly() {
require(isOver_ == false, 'notOver_only');
_;
}
// Getters -----------------------------------------------------------------
/// owner address
function getCEOAddress()
public view returns(address)
{
return CEOAddress;
}
/// counter from random number generator
function counter()
internal view returns(uint32)
{
return counter_;
}
// tokens sold by stage ...
function stageTokensBought(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].bought;
}
// stage softcap
function stageSoftcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].softcap;
}
/// stage hardcap
function stageHardcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].hardcap;
}
/// stage Start Date
function stageStartDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].startDate;
}
/// stage Finish Date
function stageEndDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].endDate;
}
/// stage token price
function stagePrice(uint _stage)
public view returns(uint)
{
return stages_[_stage].price;
}
// Genome Logic -----------------------------------------------------------------
/// within the prelase , the dragons are generated, which are the ancestors of the destiny
/// newborns have a high chance of mutation and are unlikely to be purebred
/// the player will have to collect the breed, crossing a lot of pets
/// In addition, you will need to pick up combat abilities
/// these characteristics are assigned to the pet when the dragon is imported to the game server.
function nextGenome()
internal returns(string)
{
uint8 n = getPseudoRandomNumber();
counter_ += 1;
return genomes_[stageIndex_][n];
}
function getPseudoRandomNumber()
internal view returns(uint8 index)
{
uint8 n = uint8(
keccak256(abi.encode(msg.sender, block.timestamp + counter_))
);
return n % TOKENS_PER_STAGE;
}
// PreSale Logic -----------------------------------------------------------------
/// Presale stage0 begin date set
/// presale start is possible only once
function setStartDate(uint32 _startDate)
external controllerOnly
{
require(stages_[0].startDate == 0, 'already_set');
stages_[0].startDate = _startDate;
stageStart_ = _startDate;
stageIndex_ = 0;
emit StageBegin(stageIndex_, stageStart_);
}
/// current stage number
/// switches to the next stage if the time has come
function stageIndex()
external view returns(uint8)
{
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now) {
return stageIndex_ + 1;
}
else {
return stageIndex_;
}
}
/// check whether the phase started
/// switch to the next stage, if necessary
function beforeBuy()
internal
{
if (stageStart_ == 0) {
revert('presale_not_started');
}
else if (stageStart_ > now) {
revert('stage_not_started');
}
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now)
{
stageIndex_ += 1;
stageStart_ = stages_[stageIndex_].startDate;
if (stageStart_ > now) {
revert('stage_not_started');
}
}
}
/// time to next midnight
function midnight()
public view returns(uint32)
{
uint32 tomorrow = uint32(now + 1 days);
uint32 remain = uint32(tomorrow % 1 days);
return tomorrow - remain;
}
/// buying a specified number of tokens
function buyTokens(uint16 numToBuy)
public payable notOverOnly returns(uint256[])
{
beforeBuy();
require(numToBuy > 0 && numToBuy <= 10, "numToBuy error");
Stage storage stage = stages_[stageIndex_];
require((stage.price * numToBuy) <= msg.value, 'price');
uint16 prevBought = stage.bought;
require(prevBought + numToBuy <= stage.hardcap, "have required tokens");
stage.bought += numToBuy;
uint256[] memory tokenIds = new uint256[](numToBuy);
bytes memory genomes = new bytes(numToBuy * 77);
uint32 genomeByteIndex = 0;
for(uint16 t = 0; t < numToBuy; t++)
{
string memory genome = nextGenome();
uint256 tokenId = EtherDragonsCore(erc721_).mintPresell(msg.sender, genome);
bytes memory genomeBytes = bytes(genome);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[genomeByteIndex++] = genomeBytes[gi];
}
tokenIds[t] = tokenId;
}
// Transfer mint fee to the fund
bank_.transfer(address(this).balance);
if (stage.bought == stage.hardcap) {
stage.endDate = uint32(now);
stageStart_ = midnight() + 1 days + 1 seconds;
if (stageIndex_ < STAGES - 1) {
stageIndex_ += 1;
}
else {
isOver_ = true;
}
}
else if (stage.bought >= stage.softcap && prevBought < stage.softcap) {
stage.endDate = midnight() + 1 days;
if (stageIndex_ < STAGES - 1) {
stages_[stageIndex_ + 1].startDate = stage.endDate + 1 days;
}
}
emit TokensBought(msg.sender, tokenIds, genomes);
return tokenIds;
}
function currTime()
public view returns(uint)
{
return now;
}
/// stages data
function getStagesInfo()
public view returns (uint256[] prices, uint16[] softcaps, uint16[] hardcaps, uint16[] boughts)
{
prices = new uint256[](STAGES);
softcaps = new uint16[](STAGES);
hardcaps = new uint16[](STAGES);
boughts = new uint16[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
prices[s] = stages_[s].price;
softcaps[s] = stages_[s].softcap;
hardcaps[s] = stages_[s].hardcap;
boughts[s] = stages_[s].bought;
}
}
/// stages dates data
function getStagesBeginEnd()
public view returns (uint32[] startDates, uint32[] endDates)
{
startDates = new uint32[](STAGES);
endDates = new uint32[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
startDates[s] = stages_[s].startDate;
endDates[s] = stages_[s].endDate;
}
}
/// returns data which genomes can be purchased at the stage
function stageGenomes(uint8 _stage)
public view returns(byte[])
{
byte[] memory genomes = new byte[](uint16(TOKENS_PER_STAGE) * 77);
uint32 gbIndex = 0;
for(uint8 tokenIndex = 0; tokenIndex < TOKENS_PER_STAGE; tokenIndex++) {
bytes memory genomeBytes = bytes(genomes_[_stage][tokenIndex]);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[gbIndex++] = genomeBytes[gi];
}
}
return genomes;
}
} | @dev Determine if token is approved for specified approvee. @param _tokenId Target token id. @param _approvee Approvee address. @return True if so. | function isApprovedFor(uint256 _tokenId, address _approvee)
public view returns(bool)
{
return approvals_[_tokenId] == _approvee;
}
| 5,397,191 | [
1,
8519,
309,
1147,
353,
20412,
364,
1269,
6617,
537,
73,
18,
225,
389,
2316,
548,
5916,
1147,
612,
18,
225,
389,
12908,
537,
73,
1716,
685,
537,
73,
1758,
18,
327,
1053,
309,
1427,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
31639,
1290,
12,
11890,
5034,
389,
2316,
548,
16,
1758,
389,
12908,
537,
73,
13,
203,
3639,
1071,
1476,
1135,
12,
6430,
13,
203,
565,
288,
203,
3639,
327,
6617,
4524,
67,
63,
67,
2316,
548,
65,
422,
389,
12908,
537,
73,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ITokenManager.sol";
import "./IUnlockRegistry.sol";
import "../lib/ERC20Manager.sol";
import "../fractionable/IFractionableERC721.sol";
import "../eip712/ITransferWithSig.sol";
import "../commons/MetaTransactionsMixin.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// Main Contract
contract TokenManager is Ownable, ITokenManager, MetaTransactionsMixin {
using ECDSA for bytes32;
using SafeERC20 for IERC20;
// .0001 precision.
uint32 public constant MATH_PRECISION = 1e4;
// Constant values for creating bonded ERC20 tokens.
uint256 public constant ERC20_INITIAL_SUPPLY = 10000e18; // 10000 units
uint256 public constant PLATFORM_CUT = 50; // .5%
// Reserve Token.
IERC20 private immutable reserveToken;
// NFT Registry
IFractionableERC721 private immutable nftRegistry;
// Unlock Registry
IUnlockRegistry private immutable unlockRegistry;
// Admin address allowed
address private validAdminAddress;
/**
* @dev Initializer for TokenManager contract
* @param _nftRegistry - NFT Registry address
* @param _reserveToken - Reserve registry address (1e18 decimals)
* @param _unlockRegistry - Unlock registry address
*/
constructor(
address _nftRegistry,
address _reserveToken,
address _unlockRegistry
) Ownable() {
// Set Reseve Token addresses
reserveToken = IERC20(_reserveToken);
// Set the NFT Registry
nftRegistry = IFractionableERC721(_nftRegistry);
// set the UnlockRegistry
unlockRegistry = IUnlockRegistry(_unlockRegistry);
}
/**
* @dev Migrate vault in case we want to upgrade the logic
* can only be called by the owner of the contract
* @param _newTokenManager - new tokenManager contract
*/
function migrateReserve(address _newTokenManager) external onlyOwner {
reserveToken.safeTransfer(
_newTokenManager,
reserveToken.balanceOf(address(this))
);
}
/**
* @dev Check if provided provided message hash and signature are OK
*/
function setAdminAddress(address _newAdmin) external onlyOwner {
validAdminAddress = _newAdmin;
}
/**
* @dev Create Card
* @param _tokenId card id
* @param _symbol card symbol
* @param _name card name
* @param _minLiquidityAmount creation value for the card
* @param _orderAmount contribution to creation value for the card
* @param _orderAdminSignature admin signature for createCard order
* @param _expiration for EIP712 order call
* @param _orderId for EIP712 order call
* @param _eip712TransferSignature EIP712 transfer signature for reserve token
*/
function createCard(
uint256 _tokenId,
string memory _symbol,
string memory _name,
uint256 _minLiquidityAmount,
uint256 _orderAmount,
bytes memory _orderAdminSignature,
// These are required for EIP712
uint256 _expiration,
bytes32 _orderId,
bytes memory _eip712TransferSignature
)
public
{
require(
nftRegistry.getBondedERC20(_tokenId) == address(0),
"createCard() - card already created"
);
// Check hashed message & admin signature
bytes32 orderHash = keccak256(
abi.encodePacked(
_tokenId,
_symbol,
_name,
_minLiquidityAmount,
block.chainid,
address(this)
)
);
require(
_isValidAdminHash(orderHash, _orderAdminSignature),
"createCard() - invalid admin signature"
);
// Transfer TSX _orderAmount from sender using EIP712 signature
ITransferWithSig(address(reserveToken)).transferWithSig(
_eip712TransferSignature,
_orderAmount,
keccak256(
abi.encodePacked(_orderId, address(reserveToken), _orderAmount)
),
_expiration,
msgSender(), // from
address(this) // to
);
// add user liquidity contribution.
(uint256 refund, bool contributionCompleted) = unlockRegistry.addContribution(
_tokenId,
msgSender(),
_orderAmount,
_minLiquidityAmount
);
if (refund > 0) {
reserveToken.transfer(msgSender(), refund);
}
if (contributionCompleted) {
_createCard(_tokenId, _symbol, _name, _minLiquidityAmount);
}
}
/**
* Swap two fractionable ERC721 tokens.
* @param _tokenId tokenId to liquidate
* @param _amount wei amount of liquidation in source token.
* @param _destTokenId tokenId to purchase.
* @param _minDstTokenAmount slippage protection
*/
function swap(
uint256 _tokenId,
uint256 _amount,
uint256 _destTokenId,
uint256 _minDstTokenAmount
)
public override
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"swap() - tokenId does not exist"
);
require(
nftRegistry.getBondedERC20(_destTokenId) != address(0),
"swap() - destTokenId does not exist"
);
uint256 reserveAmount = nftRegistry.estimateBondedERC20Value(
_tokenId,
_amount
);
uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens(
_destTokenId,
reserveAmount
);
require(
estimatedTokens >= _minDstTokenAmount,
"swap() - dst amount < minimum requested"
);
// Burn src tokens and mint dst token. Does not takes tx fees
nftRegistry.burnBondedERC20(_tokenId, msgSender(), _amount, reserveAmount);
nftRegistry.mintBondedERC20(_destTokenId, msgSender(), estimatedTokens, reserveAmount);
}
/**
* Estimate Swap between two fractionable ERC721 tokens.
* @param _tokenId tokenId to liquidate
* @param _amount wei amount of liquidation in source token.
* @param _destTokenId tokenId to purchase.
*/
function estimateSwap(
uint256 _tokenId,
uint256 _amount,
uint256 _destTokenId
)
public view override returns (uint expectedRate, uint reserveImpact)
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"estimateSwap() - tokenId does not exist"
);
require(
nftRegistry.getBondedERC20(_destTokenId) != address(0),
"estimateSwap() - destTokenId does not exist"
);
// get reserve amount from selling _amount of tokenId
uint256 reserveAmount = nftRegistry.estimateBondedERC20Value(
_tokenId,
_amount
);
// Get amount of _destTokenId tokens
uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens(
_destTokenId,
reserveAmount
);
address bondedToken = nftRegistry.getBondedERC20(_destTokenId);
// Return the expected exchange rate and slippage in 1e18 precision
expectedRate = (estimatedTokens * 1e18) / _amount;
reserveImpact = (reserveAmount * 1e18) / ERC20Manager.poolBalance(bondedToken);
}
/**
* Purchase of a fractionable ERC721 using reserve token
* @param _tokenId tokenId to purchase
* @param _paymentAmount wei payment amount in reserve token
* @param _minDstTokenAmount slippage protection
* @param _expiration for EIP712 order call
* @param _orderId for EIP712 order call
* @param _eip712TransferSignature EIP712 transfer signature for reserve token
*/
function purchase(
uint256 _tokenId,
uint256 _paymentAmount,
uint256 _minDstTokenAmount,
// EIP712 sigTransfer
uint256 _expiration,
bytes32 _orderId,
bytes memory _eip712TransferSignature
)
public override
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"purchase() - tokenId does not exist"
);
// Transfer TSX _paymentAmount from sender using EIP712 signature
ITransferWithSig(address(reserveToken)).transferWithSig(
_eip712TransferSignature,
_paymentAmount,
keccak256(
abi.encodePacked(_orderId, address(reserveToken), _paymentAmount)
),
_expiration,
msgSender(), // from
address(this) // to
);
// Calc fees
uint256 pFees = (_paymentAmount * PLATFORM_CUT) / MATH_PRECISION;
// Get effective amount after tx fees
uint256 effectiveReserveAmount = _paymentAmount - pFees;
// Burn reserve Tx Fees
ERC20Burnable(address(reserveToken)).burn(pFees);
// The estimated amount of bonded tokens for reserve
uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens(
_tokenId,
effectiveReserveAmount
);
require(
estimatedTokens >= _minDstTokenAmount,
"purchase() - dst amount < minimum requested"
);
// Issue fractionables to msg sender.
nftRegistry.mintBondedERC20(
_tokenId,
msgSender(),
estimatedTokens,
effectiveReserveAmount
);
}
/**
* Estimate Purchase of a fractionable ERC721 using reserve tokens
* @param _tokenId tokenId to purchase
* @param _paymentAmount wei payment amount in reserve token
*/
function estimatePurchase(
uint256 _tokenId,
uint256 _paymentAmount
)
public view override returns (uint expectedRate, uint reserveImpact)
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"estimatePurchase() - tokenId does not exist"
);
// Calc fees
uint256 pFees = (_paymentAmount * PLATFORM_CUT) / MATH_PRECISION;
// Get effective amount after tx fees
uint256 effectiveReserveAmount = _paymentAmount - pFees;
// Get estimated amount of _tokenId for effectiveReserveAmount
uint256 estimatedTokens = nftRegistry.estimateBondedERC20Tokens(
_tokenId,
effectiveReserveAmount
);
address bondedToken = nftRegistry.getBondedERC20(_tokenId);
// Return the expected exchange rate and impact on reserve
expectedRate = (estimatedTokens * 1e18) / _paymentAmount;
reserveImpact = (effectiveReserveAmount * 1e18) / ERC20Manager.poolBalance(bondedToken);
}
/**
* Liquidate a fractionable ERC721 for reserve token
* @param _tokenId tokenId to liquidate
* @param _liquidationAmount wei amount for liquidate
* @param _minDstTokenAmount slippage protection
*/
function liquidate(
uint256 _tokenId,
uint256 _liquidationAmount,
uint256 _minDstTokenAmount
)
public override
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"liquidate() - tokenId does not exist"
);
// Estimate reserve for selling _tokenId
uint256 reserveAmount = nftRegistry.estimateBondedERC20Value(
_tokenId,
_liquidationAmount
);
require(
reserveAmount >= _minDstTokenAmount,
"liquidate() - dst amount < minimum requested"
);
// Burn selled tokens.
nftRegistry.burnBondedERC20(
_tokenId,
msgSender(),
_liquidationAmount,
reserveAmount
);
// fees
uint256 pFee = (reserveAmount * PLATFORM_CUT) / MATH_PRECISION;
// Burn reserve Tx Fees
ERC20Burnable(address(reserveToken)).burn(pFee);
// Get effective amount after tx fees
uint256 effectiveReserveAmount = reserveAmount - pFee;
// Trade reserve to sTSX and send to liquidator
reserveToken.safeTransfer(
msgSender(),
effectiveReserveAmount
);
}
/**
* Estimate Liquidation of a fractionable ERC721 for sTSX
* @param _tokenId tokenId to liquidate
* @param _liquidationAmount wei amount for liquidate
*/
function estimateLiquidate(
uint256 _tokenId,
uint256 _liquidationAmount
)
public view override returns (uint expectedRate, uint reserveImpact)
{
require(
nftRegistry.getBondedERC20(_tokenId) != address(0),
"estimateLiquidate() - tokenId does not exist"
);
address bondedToken = nftRegistry.getBondedERC20(_tokenId);
uint256 reserveAmount = nftRegistry.estimateBondedERC20Value(
_tokenId,
_liquidationAmount
);
// Calc fees
uint256 pFees = (reserveAmount * PLATFORM_CUT) / MATH_PRECISION;
// Get effective amount after tx fees
uint256 effectiveReserveAmount = reserveAmount - pFees;
// Return the expected exchange rate and slippage in 1e18 precision
expectedRate = (_liquidationAmount * 1e18) / effectiveReserveAmount;
reserveImpact = (reserveAmount * 1e18) / ERC20Manager.poolBalance(bondedToken);
}
/**
* Internal create ERC721 and issues first bonded tokens
* @param _tokenId tokenId to create
* @param _symbol token symbol
* @param _name token name
* @param _minLiquidityAmount creation value for the card
*/
function _createCard(
uint256 _tokenId,
string memory _symbol,
string memory _name,
uint256 _minLiquidityAmount
)
private
{
// Create NFT. sets owner to this contract's owner
nftRegistry.mintToken(_tokenId, owner(), _symbol, _name);
nftRegistry.mintBondedERC20(
_tokenId,
address(this),
ERC20_INITIAL_SUPPLY,
_minLiquidityAmount
);
address bondedToken = nftRegistry.getBondedERC20(_tokenId);
address[] memory senders = unlockRegistry.getContributorsFor(_tokenId);
// send shares to liquidity contributors
for (uint256 i = 0; i < senders.length; i++) {
// calculate
uint256 contribuition = unlockRegistry.getSenderContributionFor(
senders[i], _tokenId
);
uint256 tokens = (ERC20_INITIAL_SUPPLY * contribuition) / _minLiquidityAmount; // amount
ERC20Manager.transfer(bondedToken, senders[i], tokens);
}
// free unused space
unlockRegistry.clearContributorsFor(_tokenId);
}
/**
* @dev Check if provided provided message hash and signature are OK
*/
function _isValidAdminHash(bytes32 _hash, bytes memory _sig) private view returns (bool) {
return validAdminAddress == _hash.toEthSignedMessageHash().recover(_sig);
}
}
| * @dev Initializer for TokenManager contract @param _nftRegistry - NFT Registry address @param _reserveToken - Reserve registry address (1e18 decimals) @param _unlockRegistry - Unlock registry address/ Set Reseve Token addresses Set the NFT Registry set the UnlockRegistry | ) Ownable() {
reserveToken = IERC20(_reserveToken);
nftRegistry = IFractionableERC721(_nftRegistry);
unlockRegistry = IUnlockRegistry(_unlockRegistry);
}
| 14,107,938 | [
1,
14729,
364,
3155,
1318,
6835,
225,
389,
82,
1222,
4243,
300,
423,
4464,
5438,
1758,
225,
389,
455,
6527,
1345,
300,
1124,
6527,
4023,
1758,
261,
21,
73,
2643,
15105,
13,
225,
389,
26226,
4243,
300,
3967,
4023,
1758,
19,
1000,
1124,
73,
537,
3155,
6138,
1000,
326,
423,
4464,
5438,
444,
326,
3967,
4243,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
14223,
6914,
1435,
288,
203,
203,
3639,
20501,
1345,
273,
467,
654,
39,
3462,
24899,
455,
6527,
1345,
1769,
203,
203,
3639,
290,
1222,
4243,
273,
11083,
5738,
429,
654,
39,
27,
5340,
24899,
82,
1222,
4243,
1769,
203,
203,
3639,
7186,
4243,
273,
467,
7087,
4243,
24899,
26226,
4243,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xBD7bd0B4650D324e3eA6f734fAA3FC37d80b7D82/sources/contracts/HeroesToken.sol | * Only Owner methods/ Add a new bundle | function addBundle(uint8 characterCount, uint256 _price)
public onlyOwner
{
require(_price > 0, "No free bundle as in free beer.");
require(characterCount > 0, "Character count is required");
require(characterCount <= 10, "Character count can be maximum 10");
require(BUNDLE < MAX_BUNDLES, "Maximum 5 bundles allowed !");
++BUNDLE;
bundles[BUNDLE-1] = characterCount;
prices[BUNDLE-1] = _price;
emit BundleAdded(BUNDLE-1, characterCount, _price);
}
| 4,505,088 | [
1,
3386,
16837,
2590,
19,
1436,
279,
394,
3440,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
527,
3405,
12,
11890,
28,
3351,
1380,
16,
2254,
5034,
389,
8694,
13,
203,
225,
1071,
1338,
5541,
203,
225,
288,
203,
565,
2583,
24899,
8694,
405,
374,
16,
315,
2279,
4843,
3440,
487,
316,
4843,
506,
264,
1199,
1769,
203,
565,
2583,
12,
11560,
1380,
405,
374,
16,
315,
7069,
1056,
353,
1931,
8863,
203,
565,
2583,
12,
11560,
1380,
1648,
1728,
16,
315,
7069,
1056,
848,
506,
4207,
1728,
8863,
203,
565,
2583,
12,
30245,
411,
4552,
67,
38,
5240,
11386,
16,
315,
13528,
1381,
11408,
2935,
401,
8863,
203,
565,
965,
30245,
31,
203,
203,
565,
11408,
63,
30245,
17,
21,
65,
273,
3351,
1380,
31,
203,
565,
19827,
63,
30245,
17,
21,
65,
273,
389,
8694,
31,
203,
565,
3626,
8539,
8602,
12,
30245,
17,
21,
16,
3351,
1380,
16,
389,
8694,
1769,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-23
*/
// File: contracts/interfaces/interestModelInterface.sol
pragma solidity 0.6.12;
interface interestModelInterface {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
// File: contracts/interfaces/marketHandlerDataStorageInterface.sol
pragma solidity 0.6.12;
interface marketHandlerDataStorageInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getMinimumInterestRate() external view returns (uint256);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function getLiquiditySensitivity() external view returns (uint256);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function getMarginCallLimit() external view returns (uint256);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
// File: contracts/SafeMath.sol
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
pragma solidity ^0.6.12;
library SafeMath {
uint256 internal constant unifiedPoint = 10 ** 18;
/******************** Safe Math********************/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "a");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "s");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "d");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a* b;
require((c / a) == b, "m");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "d");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "m");
}
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/interestModel/interestModel.sol
pragma solidity 0.6.12;
/**
* @title Bifi interestModel Contract
* @notice Contract for interestModel
* @author Bifi
*/
contract interestModel is interestModelInterface, InterestErrors {
using SafeMath for uint256;
address owner;
mapping(address => bool) public operators;
uint256 constant blocksPerYear = 2102400;
uint256 constant unifiedPoint = 10 ** 18;
uint256 minRate;
uint256 basicSensitivity;
/* jump rate model prams */
uint256 jumpPoint;
uint256 jumpSensitivity;
uint256 spreadRate;
struct InterestUpdateModel {
uint256 SIR;
uint256 BIR;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
uint256 userDepositAmount;
uint256 userBorrowAmount;
uint256 deltaDepositAmount;
uint256 deltaBorrowAmount;
uint256 globalDepositEXR;
uint256 globalBorrowEXR;
uint256 userDepositEXR;
uint256 userBorrowEXR;
uint256 actionDepositEXR;
uint256 actionBorrowEXR;
uint256 deltaDepositEXR;
uint256 deltaBorrowEXR;
bool depositNegativeFlag;
bool borrowNegativeFlag;
}
modifier onlyOwner {
require(msg.sender == owner, ONLY_OWNER);
_;
}
modifier onlyOperator {
address sender = msg.sender;
require(operators[sender] || sender == owner, "Only Operators");
_;
}
/**
* @dev Construct a new interestModel contract
* @param _minRate minimum interest rate
* @param _jumpPoint Threshold of utilizationRate to which normal interest model
* @param _basicSensitivity liquidity basicSensitivity
* @param _jumpSensitivity The value used to calculate the BIR if the utilizationRate is greater than the jumpPoint.
* @param _spreadRate spread rate
*/
constructor (uint256 _minRate, uint256 _jumpPoint, uint256 _basicSensitivity, uint256 _jumpSensitivity, uint256 _spreadRate) public
{
address sender = msg.sender;
owner = sender;
operators[owner] = true;
minRate = _minRate;
basicSensitivity = _basicSensitivity;
jumpPoint = _jumpPoint;
jumpSensitivity = _jumpSensitivity;
spreadRate = _spreadRate;
}
/**
* @dev Replace the owner of the handler
* @param _owner the address of the new owner
* @return true (TODO: validate results)
*/
function ownershipTransfer(address payable _owner) onlyOwner external returns (bool)
{
owner = _owner;
return true;
}
/**
* @dev Get the address of owner
* @return the address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev set Operator or not
* @param _operator the address of the operator
* @param flag operator permission
* @return true (TODO: validate results)
*/
function setOperators(address payable _operator, bool flag) onlyOwner external returns (bool) {
operators[_operator] = flag;
return true;
}
/**
* @dev Calculates interest amount for a user
* @param handlerDataStorageAddr The address of handlerDataStorage contract
* @param userAddr The address of user
* @param isView Select _view (before action) or _get (after action) function for calculation
* @return (bool, uint256, uint256, bool, uint256, uint256)
*/
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view override returns (bool, uint256, uint256, bool, uint256, uint256)
{
if (isView)
{
return _viewInterestAmount(handlerDataStorageAddr, userAddr);
}
else
{
return _getInterestAmount(handlerDataStorageAddr, userAddr);
}
}
/**
* @dev Calculates interest amount for a user (before user action)
* @param handlerDataStorageAddr The address of handlerDataStorage contract
* @param userAddr The address of user
* @return (bool, uint256, uint256, bool, uint256, uint256)
*/
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view override returns (bool, uint256, uint256, bool, uint256, uint256)
{
return _viewInterestAmount(handlerDataStorageAddr, userAddr);
}
/**
* @dev Get Supply Interest Rate (SIR) and Borrow Interest Rate (BIR) (external)
* @param totalDepositAmount The amount of total deposit
* @param totalBorrowAmount The amount of total borrow
* @return (uint256, uin256)
*/
function getSIRandBIR(uint256 totalDepositAmount, uint256 totalBorrowAmount) external view override returns (uint256, uint256)
{
return _getSIRandBIR(totalDepositAmount, totalBorrowAmount);
}
/**
* @dev Calculates interest amount for a user (after user action)
* @param handlerDataStorageAddr The address of handlerDataStorage contract
* @param userAddr The address of user
* @return (bool, uint256, uint256, bool, uint256, uint256)
*/
function _getInterestAmount(address handlerDataStorageAddr, address payable userAddr) internal view returns (bool, uint256, uint256, bool, uint256, uint256)
{
marketHandlerDataStorageInterface handlerDataStorage = marketHandlerDataStorageInterface(handlerDataStorageAddr);
uint256 delta = handlerDataStorage.getInactiveActionDelta();
uint256 actionDepositEXR;
uint256 actionBorrowEXR;
(actionDepositEXR, actionBorrowEXR) = handlerDataStorage.getActionEXR();
return _calcInterestAmount(handlerDataStorageAddr, userAddr, delta, actionDepositEXR, actionBorrowEXR);
}
/**
* @dev Calculates interest amount for a user (before user action)
* @param handlerDataStorageAddr The address of handlerDataStorage contract
* @param userAddr The address of user
* @return (bool, uint256, uint256, bool, uint256, uint256)
*/
function _viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) internal view returns (bool, uint256, uint256, bool, uint256, uint256)
{
marketHandlerDataStorageInterface handlerDataStorage = marketHandlerDataStorageInterface(handlerDataStorageAddr);
uint256 blockDelta = block.number.sub(handlerDataStorage.getLastUpdatedBlock());
/* check action in block */
uint256 globalDepositEXR;
uint256 globalBorrowEXR;
(globalDepositEXR, globalBorrowEXR) = handlerDataStorage.getGlobalEXR();
return _calcInterestAmount(handlerDataStorageAddr, userAddr, blockDelta, globalDepositEXR, globalBorrowEXR);
}
/**
* @dev Calculate interest amount for a user with BIR and SIR (interal)
* @param handlerDataStorageAddr The address of handlerDataStorage contract
* @param userAddr The address of user
* @return (bool, uint256, uint256, bool, uint256, uint256)
*/
function _calcInterestAmount(address handlerDataStorageAddr, address payable userAddr, uint256 delta, uint256 actionDepositEXR, uint256 actionBorrowEXR) internal view returns (bool, uint256, uint256, bool, uint256, uint256)
{
InterestUpdateModel memory interestUpdateModel;
marketHandlerDataStorageInterface handlerDataStorage = marketHandlerDataStorageInterface(handlerDataStorageAddr);
(interestUpdateModel.depositTotalAmount, interestUpdateModel.borrowTotalAmount, interestUpdateModel.userDepositAmount, interestUpdateModel.userBorrowAmount) = handlerDataStorage.getAmount(userAddr);
(interestUpdateModel.SIR, interestUpdateModel.BIR) = _getSIRandBIRonBlock(interestUpdateModel.depositTotalAmount, interestUpdateModel.borrowTotalAmount);
(interestUpdateModel.userDepositEXR, interestUpdateModel.userBorrowEXR) = handlerDataStorage.getUserEXR(userAddr);
/* deposit start */
interestUpdateModel.globalDepositEXR = _getNewGlobalEXR(actionDepositEXR, interestUpdateModel.SIR, delta);
(interestUpdateModel.depositNegativeFlag, interestUpdateModel.deltaDepositAmount) = _getDeltaAmount(interestUpdateModel.userDepositAmount, interestUpdateModel.globalDepositEXR, interestUpdateModel.userDepositEXR);
/* deposit done */
/* borrow start */
interestUpdateModel.globalBorrowEXR = _getNewGlobalEXR(actionBorrowEXR, interestUpdateModel.BIR, delta);
(interestUpdateModel.borrowNegativeFlag, interestUpdateModel.deltaBorrowAmount) = _getDeltaAmount(interestUpdateModel.userBorrowAmount, interestUpdateModel.globalBorrowEXR, interestUpdateModel.userBorrowEXR);
/* borrow done */
return (interestUpdateModel.depositNegativeFlag, interestUpdateModel.deltaDepositAmount, interestUpdateModel.globalDepositEXR, interestUpdateModel.borrowNegativeFlag, interestUpdateModel.deltaBorrowAmount, interestUpdateModel.globalBorrowEXR);
}
/**
* @dev Calculates the utilization rate of market
* @param depositTotalAmount The total amount of deposit
* @param borrowTotalAmount The total amount of borrow
* @return The utilitization rate of market
*/
function _getUtilizationRate(uint256 depositTotalAmount, uint256 borrowTotalAmount) internal pure returns (uint256)
{
if ((depositTotalAmount == 0) && (borrowTotalAmount == 0))
{
return 0;
}
return borrowTotalAmount.unifiedDiv(depositTotalAmount);
}
/**
* @dev Get SIR and BIR (internal)
* @param depositTotalAmount The amount of total deposit
* @param borrowTotalAmount The amount of total borrow
* @return (uint256, uin256)
*/
function _getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) internal view returns (uint256, uint256)
// TODO: update comment(jump rate)
{
/* UtilRate = TotalBorrow / (TotalDeposit + TotalBorrow) */
uint256 utilRate = _getUtilizationRate(depositTotalAmount, borrowTotalAmount);
uint256 BIR;
uint256 _jmpPoint = jumpPoint;
/* BIR = minimumRate + (UtilRate * liquiditySensitivity) */
if(utilRate < _jmpPoint) {
BIR = utilRate.unifiedMul(basicSensitivity).add(minRate);
} else {
/*
Formula : BIR = minRate + jumpPoint * basicSensitivity + (utilRate - jumpPoint) * jumpSensitivity
uint256 _baseBIR = _jmpPoint.unifiedMul(basicSensitivity);
uint256 _jumpBIR = utilRate.sub(_jmpPoint).unifiedMul(jumpSensitivity);
BIR = minRate.add(_baseBIR).add(_jumpBIR);
*/
BIR = minRate
.add( _jmpPoint.unifiedMul(basicSensitivity) )
.add( utilRate.sub(_jmpPoint).unifiedMul(jumpSensitivity) );
}
/* SIR = UtilRate * BIR */
uint256 SIR = utilRate.unifiedMul(BIR).unifiedMul(spreadRate);
return (SIR, BIR);
}
/**
* @dev Get SIR and BIR per block (internal)
* @param depositTotalAmount The amount of total deposit
* @param borrowTotalAmount The amount of total borrow
* @return (uint256, uin256)
*/
function _getSIRandBIRonBlock(uint256 depositTotalAmount, uint256 borrowTotalAmount) internal view returns (uint256, uint256)
{
uint256 SIR;
uint256 BIR;
(SIR, BIR) = _getSIRandBIR(depositTotalAmount, borrowTotalAmount);
return ( SIR.div(blocksPerYear), BIR.div(blocksPerYear) );
}
/**
* @dev Calculates the rate of globalEXR (for borrowEXR or depositEXR)
* @param actionEXR The rate of actionEXR
* @param interestRate The rate of interest
* @param delta The interval between user actions (in block)
* @return The amount of newGlobalEXR
*/
function _getNewGlobalEXR(uint256 actionEXR, uint256 interestRate, uint256 delta) internal pure returns (uint256)
{
return interestRate.mul(delta).add(unifiedPoint).unifiedMul(actionEXR);
}
/**
* @dev Calculates difference between globalEXR and userEXR
* @param unifiedAmount The unifiedAmount (for fixed decimal number)
* @param globalEXR The amount of globalEXR
* @param userEXR The amount of userEXR
* @return (bool, uint256)
*/
function _getDeltaAmount(uint256 unifiedAmount, uint256 globalEXR, uint256 userEXR) internal pure returns (bool, uint256)
{
uint256 deltaEXR;
bool negativeFlag;
uint256 deltaAmount;
if (unifiedAmount != 0)
{
(negativeFlag, deltaEXR) = _getDeltaEXR(globalEXR, userEXR);
deltaAmount = unifiedAmount.unifiedMul(deltaEXR);
}
return (negativeFlag, deltaAmount);
}
/**
* @dev Calculates the delta EXR between globalEXR and userEXR
* @param newGlobalEXR The new globalEXR
* @param lastUserEXR The last userEXR
* @return (bool, uint256)
*/
function _getDeltaEXR(uint256 newGlobalEXR, uint256 lastUserEXR) internal pure returns (bool, uint256)
{
uint256 EXR = newGlobalEXR.unifiedDiv(lastUserEXR);
if (EXR >= unifiedPoint)
{
return ( false, EXR.sub(unifiedPoint) );
}
return ( true, unifiedPoint.sub(EXR) );
}
//TODO: Need comment
function getMinRate() external view returns (uint256) {
return minRate;
}
function setMinRate(uint256 _minRate) external onlyOperator returns (bool) {
minRate = _minRate;
return true;
}
function getBasicSensitivity() external view returns (uint256) {
return basicSensitivity;
}
function setBasicSensitivity(uint256 _sensitivity) external onlyOperator returns (bool) {
basicSensitivity = _sensitivity;
return true;
}
function getJumpPoint() external view returns (uint256) {
return jumpPoint;
}
function setJumpPoint(uint256 _jumpPoint) external onlyOperator returns (bool) {
jumpPoint = _jumpPoint;
return true;
}
function getJumpSensitivity() external view returns (uint256) {
return jumpSensitivity;
}
function setJumpSensitivity(uint256 _sensitivity) external onlyOperator returns (bool) {
jumpSensitivity = _sensitivity;
return true;
}
function getSpreadRate() external view returns (uint256) {
return spreadRate;
}
function setSpreadRate(uint256 _spreadRate) external onlyOperator returns (bool) {
spreadRate = _spreadRate;
return true;
}
}
// File: contracts/truffleKit/InterestModel.sol
pragma solidity 0.6.12;
contract LinkInterestModel is interestModel {
constructor(
uint256 _minRate,
uint256 _jumpPoint,
uint256 _basicSensitivity,
uint256 _jumpSensitivity,
uint256 _spreadRate
)
interestModel(
_minRate,
_jumpPoint,
_basicSensitivity,
_jumpSensitivity,
_spreadRate
) public {}
} | * @dev Calculates the rate of globalEXR (for borrowEXR or depositEXR) @param actionEXR The rate of actionEXR @param interestRate The rate of interest @param delta The interval between user actions (in block) @return The amount of newGlobalEXR/ | function _getNewGlobalEXR(uint256 actionEXR, uint256 interestRate, uint256 delta) internal pure returns (uint256)
{
return interestRate.mul(delta).add(unifiedPoint).unifiedMul(actionEXR);
}
| 2,263,641 | [
1,
10587,
326,
4993,
434,
2552,
2294,
54,
261,
1884,
29759,
2294,
54,
578,
443,
1724,
2294,
54,
13,
225,
1301,
2294,
54,
1021,
4993,
434,
1301,
2294,
54,
225,
16513,
4727,
1021,
4993,
434,
16513,
225,
3622,
1021,
3673,
3086,
729,
4209,
261,
267,
1203,
13,
327,
1021,
3844,
434,
394,
5160,
2294,
54,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
389,
588,
1908,
5160,
2294,
54,
12,
11890,
5034,
1301,
2294,
54,
16,
2254,
5034,
16513,
4727,
16,
2254,
5034,
3622,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
203,
202,
95,
203,
202,
202,
2463,
16513,
4727,
18,
16411,
12,
9878,
2934,
1289,
12,
318,
939,
2148,
2934,
318,
939,
27860,
12,
1128,
2294,
54,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: zos-lib/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @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 is Initializable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initialize(address sender) public initializer {
_owner = sender;
}
/**
* @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 OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts/lib/SafeMathInt.sol
/*
MIT License
Copyright (c) 2018 requestnetwork
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.
*/
pragma solidity >=0.4.24;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// File: contracts/lib/UInt256Lib.sol
pragma solidity >=0.4.24;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a)
internal
pure
returns (int256)
{
require(a <= MAX_INT256);
return int256(a);
}
}
// File: contracts/interface/ISeigniorageShares.sol
pragma solidity >=0.4.24;
interface ISeigniorageShares {
function setDividendPoints(address account, uint256 totalDividends) external returns (bool);
function mintShares(address account, uint256 amount) external returns (bool);
function lastDividendPoints(address who) external view returns (uint256);
function externalRawBalanceOf(address who) external view returns (uint256);
function externalTotalSupply() external view returns (uint256);
}
// File: openzeppelin-eth/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
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);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string name, string symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: contracts/dollars.sol
pragma solidity >=0.4.24;
interface IDollarPolicy {
function getUsdSharePrice() external view returns (uint256 price);
}
/*
* Dollar ERC20
*/
contract Dollars is ERC20Detailed, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogContraction(uint256 indexed epoch, uint256 dollarsToBurn);
event LogRebasePaused(bool paused);
event LogBurn(address indexed from, uint256 value);
event LogClaim(address indexed from, uint256 value);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
address public sharesAddress;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
// coins needing to be burned (9 decimals)
uint256 private _remainingDollarsToBeBurned;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_DOLLAR_SUPPLY = 1 * 10**6 * 10**DECIMALS;
uint256 private _maxDiscount;
modifier validDiscount(uint256 discount) {
require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH');
_;
}
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private constant POINT_MULTIPLIER = 10 ** 9;
uint256 private _totalDividendPoints;
uint256 private _unclaimedDividends;
ISeigniorageShares shares;
mapping(address => uint256) private _dollarBalances;
// This is denominated in Dollars, because the cents-dollars conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedDollars;
IDollarPolicy dollarPolicy;
uint256 public burningDiscount; // percentage (10 ** 9 Decimals)
uint256 public defaultDiscount; // discount on first negative rebase
uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions
uint256 public minimumBonusThreshold;
bool reEntrancyMutex;
bool reEntrancyRebaseMutex;
address public uniswapV2Pool;
modifier uniqueAddresses(address addr1, address addr2) {
require(addr1 != addr2, "Addresses are not unique");
_;
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
dollarPolicy = IDollarPolicy(monetaryPolicy_);
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
function setUniswapV2SyncAddress(address uniswapV2Pair_)
external
onlyOwner
{
uniswapV2Pool = uniswapV2Pair_;
}
function test()
external
onlyOwner
{
uniswapV2Pool.call(abi.encodeWithSignature('sync()'));
}
function setBurningDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
burningDiscount = discount;
}
// amount in is 10 ** 9 decimals
function burn(uint256 amount)
external
updateAccount(msg.sender)
{
require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
reEntrancyMutex = true;
require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE');
require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
_burn(msg.sender, amount);
reEntrancyMutex = false;
}
function setDefaultDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDiscount = discount;
}
function setMaxDiscount(uint256 discount)
external
onlyOwner
{
_maxDiscount = discount;
}
function setDefaultDailyBonusDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDailyBonusDiscount = discount;
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
// action of claiming funds
function claimDividends(address account) external updateAccount(account) returns (uint256) {
uint256 owing = dividendsOwing(account);
return owing;
}
function setMinimumBonusThreshold(uint256 minimum)
external
onlyOwner
{
require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH');
minimumBonusThreshold = minimum;
}
/**
* @dev Notifies Dollars contract about a new rebase cycle.
* @param supplyDelta The number of new dollar tokens to add into circulation via expansion.
* @return The total number of dollars after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
whenRebaseNotPaused
returns (uint256)
{
reEntrancyRebaseMutex = true;
uint256 burningDefaultDiscount = burningDiscount.add(defaultDailyBonusDiscount);
if (supplyDelta == 0) {
if (_remainingDollarsToBeBurned > minimumBonusThreshold) {
burningDiscount = burningDefaultDiscount > _maxDiscount ? _maxDiscount : burningDefaultDiscount;
} else {
burningDiscount = defaultDiscount;
}
emit LogRebase(epoch, _totalSupply);
} else if (supplyDelta < 0) {
uint256 dollarsToBurn = uint256(supplyDelta.abs());
uint256 tenPercent = _totalSupply.div(10);
if (dollarsToBurn > tenPercent) { // maximum contraction is 10% of the total USD Supply
dollarsToBurn = tenPercent;
}
if (dollarsToBurn.add(_remainingDollarsToBeBurned) > _totalSupply) {
dollarsToBurn = _totalSupply.sub(_remainingDollarsToBeBurned);
}
if (_remainingDollarsToBeBurned > minimumBonusThreshold) {
burningDiscount = burningDefaultDiscount > _maxDiscount ?
_maxDiscount : burningDefaultDiscount;
} else {
burningDiscount = defaultDiscount; // default 1%
}
_remainingDollarsToBeBurned = _remainingDollarsToBeBurned.add(dollarsToBurn);
emit LogContraction(epoch, dollarsToBurn);
} else {
disburse(uint256(supplyDelta));
uniswapV2Pool.call(abi.encodeWithSignature('sync()'));
emit LogRebase(epoch, _totalSupply);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
}
reEntrancyRebaseMutex = false;
return _totalSupply;
}
function initialize(address owner_, address seigniorageAddress)
public
initializer
{
ERC20Detailed.initialize("Dollars", "USD", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
_totalSupply = INITIAL_DOLLAR_SUPPLY;
sharesAddress = seigniorageAddress;
shares = ISeigniorageShares(seigniorageAddress);
_dollarBalances[owner_] = _totalSupply;
_maxDiscount = 50 * 10 ** 9; // 50%
defaultDiscount = 1 * 10 ** 9; // 1%
burningDiscount = defaultDiscount;
defaultDailyBonusDiscount = 1 * 10 ** 9; // 1%
minimumBonusThreshold = 100 * 10 ** 9; // 100 dollars is the minimum threshold. Anything above warrants increased discount
emit Transfer(address(0x0), owner_, _totalSupply);
}
function dividendsOwing(address account) public view returns (uint256) {
if (_totalDividendPoints > shares.lastDividendPoints(account)) {
uint256 newDividendPoints = _totalDividendPoints.sub(shares.lastDividendPoints(account));
uint256 sharesBalance = shares.externalRawBalanceOf(account);
return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER);
} else {
return 0;
}
}
// auto claim modifier
// if user is owned, we pay out immedietly
// if user is not owned, we prevent them from claiming until the next rebase
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if (owing != 0) {
_unclaimedDividends = _unclaimedDividends.sub(owing);
_dollarBalances[account] += owing;
}
shares.setDividendPoints(account, _totalDividendPoints);
emit LogClaim(account, owing);
_;
}
/**
* @return The total number of dollars.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _dollarBalances[who].add(dividendsOwing(who));
}
function getRemainingDollarsToBeBurned()
public
view
returns (uint256)
{
return _remainingDollarsToBeBurned;
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
uniqueAddresses(msg.sender, to)
validRecipient(to)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(value);
_dollarBalances[to] = _dollarBalances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedDollars[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
updateAccount(from)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
_allowedDollars[from][msg.sender] = _allowedDollars[from][msg.sender].sub(value);
_dollarBalances[from] = _dollarBalances[from].sub(value);
_dollarBalances[to] = _dollarBalances[to].add(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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
uniqueAddresses(msg.sender, spender)
validRecipient(spender)
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedDollars[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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
uniqueAddresses(msg.sender, spender)
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedDollars[msg.sender][spender] =
_allowedDollars[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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
uniqueAddresses(msg.sender, spender)
updateAccount(spender)
updateAccount(msg.sender)
returns (bool)
{
uint256 oldValue = _allowedDollars[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedDollars[msg.sender][spender] = 0;
} else {
_allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]);
return true;
}
function consultBurn(uint256 amount)
public
returns (uint256)
{
require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE');
require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID');
require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); // 1 share = x dollars
uint256 decimals = 10 ** 9;
uint256 percentDenominator = 100;
usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); // 10^9
uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); // 10^9
return sharesToMint;
}
function unclaimedDividends()
public
view
returns (uint256)
{
return _unclaimedDividends;
}
function totalDividendPoints()
public
view
returns (uint256)
{
return _totalDividendPoints;
}
function disburse(uint256 amount) internal returns (bool) {
_totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(shares.externalTotalSupply()));
_totalSupply = _totalSupply.add(amount);
_unclaimedDividends = _unclaimedDividends.add(amount);
return true;
}
function _burn(address account, uint256 amount)
internal
{
_totalSupply = _totalSupply.sub(amount);
_dollarBalances[account] = _dollarBalances[account].sub(amount);
uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); // 1 share = x dollars
uint256 decimals = 10 ** 9;
uint256 percentDenominator = 100;
usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); // 10^9
uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); // 10^9
_remainingDollarsToBeBurned = _remainingDollarsToBeBurned.sub(amount);
shares.mintShares(account, sharesToMint);
emit Transfer(account, address(0), amount);
emit LogBurn(account, amount);
}
}
// File: contracts/dollarsPolicy.sol
pragma solidity >=0.4.24;
/*
* Dollar Policy
*/
interface IDecentralizedOracle {
function update() external;
function consult(address token, uint amountIn) external view returns (uint amountOut);
}
contract DollarsPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
Dollars public dollars;
// Provides the current CPI, as an 18 decimal fixed point number.
IDecentralizedOracle public sharesPerUsdOracle;
IDecentralizedOracle public ethPerUsdOracle;
IDecentralizedOracle public ethPerUsdcOracle;
uint256 public deviationThreshold;
uint256 public rebaseLag;
uint256 private cpi;
uint256 public minRebaseTimeIntervalSec;
uint256 public lastRebaseTimestampSec;
uint256 public rebaseWindowOffsetSec;
uint256 public rebaseWindowLengthSec;
uint256 public epoch;
address WETH_ADDRESS;
address SHARE_ADDRESS;
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
address public orchestrator;
bool private initializedOracle;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator);
_;
}
uint256 public minimumDollarCirculation;
function getUsdSharePrice() external view returns (uint256) {
sharesPerUsdOracle.update();
uint256 shareDecimals = 10 ** 9;
uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); // 10^9 decimals
return sharePrice;
}
function rebase() external onlyOrchestrator {
require(inRebaseWindow(), "OUTISDE_REBASE");
require(initializedOracle, 'ORACLE_NOT_INITIALIZED');
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "MIN_TIME_NOT_MET");
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
sharesPerUsdOracle.update();
ethPerUsdOracle.update();
ethPerUsdcOracle.update();
uint256 wethDecimals = 10 ** 18;
uint256 shareDecimals = 10 ** 9;
uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 1 * wethDecimals); // 10^18 decimals ropsten, 10^6 mainnet
uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 1 * wethDecimals); // 10^9 decimals
uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(10 ** 21) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet
.div(ethUsdPrice);
uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); // 10^9 decimals
uint256 shareExchangeRate = sharePrice.mul(dollarCoinExchangeRate).div(shareDecimals); // 10^18 decimals
uint256 targetRate = cpi;
if (dollarCoinExchangeRate > MAX_RATE) {
dollarCoinExchangeRate = MAX_RATE;
}
// dollarCoinExchangeRate & targetRate arre 10^18 decimals
int256 supplyDelta = computeSupplyDelta(dollarCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals
// Apply the Dampening factor.
// supplyDelta = supplyDelta.mul(10 ** 9).div(rebaseLag.toInt256Safe());
uint256 algorithmicLag_ = getAlgorithmicRebaseLag(supplyDelta);
require(algorithmicLag_ != 0, "algorithmic rate must be positive");
rebaseLag = algorithmicLag_;
supplyDelta = supplyDelta.mul(10 ** 9).div(algorithmicLag_.toInt256Safe()); // v 0.0.1
// check on the expansionary side
if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe();
}
// check on the contraction side
if (supplyDelta < 0 && dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(dollars.getRemainingDollarsToBeBurned())).toInt256Safe();
}
// set minimum floor
if (supplyDelta < 0 && dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs()))) < minimumDollarCirculation) {
supplyDelta = (dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned()).sub(minimumDollarCirculation)).toInt256Safe();
}
uint256 supplyAfterRebase;
if (supplyDelta < 0) { // contraction, we send the amount of shares to mint
uint256 dollarsToBurn = uint256(supplyDelta.abs());
supplyAfterRebase = dollars.rebase(epoch, (dollarsToBurn).toInt256Safe().mul(-1));
} else { // expansion, we send the amount of dollars to mint
supplyAfterRebase = dollars.rebase(epoch, supplyDelta);
}
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, dollarCoinExchangeRate, cpi, supplyDelta, now);
}
function setOrchestrator(address orchestrator_)
external
onlyOwner
{
orchestrator = orchestrator_;
}
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyOwner
{
deviationThreshold = deviationThreshold_;
}
function setCpi(uint256 cpi_)
external
onlyOwner
{
require(cpi_ != 0);
cpi = cpi_;
}
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ != 0);
rebaseLag = rebaseLag_;
}
function initializeOracles(
address sharesPerUsdOracleAddress,
address ethPerUsdOracleAddress,
address ethPerUsdcOracleAddress
) external onlyOwner {
require(!initializedOracle, 'ALREADY_INITIALIZED_ORACLE');
sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress);
ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress);
ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress);
initializedOracle = true;
}
function changeOracles(
address sharesPerUsdOracleAddress,
address ethPerUsdOracleAddress,
address ethPerUsdcOracleAddress
) external onlyOwner {
sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress);
ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress);
ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress);
}
function setWethAddress(address wethAddress)
external
onlyOwner
{
WETH_ADDRESS = wethAddress;
}
function setShareAddress(address shareAddress)
external
onlyOwner
{
SHARE_ADDRESS = shareAddress;
}
function setMinimumDollarCirculation(uint256 minimumDollarCirculation_)
external
onlyOwner
{
minimumDollarCirculation = minimumDollarCirculation_;
}
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyOwner
{
require(minRebaseTimeIntervalSec_ != 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
function initialize(address owner_, Dollars dollars_)
public
initializer
{
Ownable.initialize(owner_);
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 50 * 10 ** 9;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug)
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
cpi = 1 * 10 ** 18;
epoch = 0;
minimumDollarCirculation = 1000000 * 10 ** 9; // 1M minimum dollar circulation
dollars = dollars_;
}
// takes current marketcap of USD and calculates the algorithmic rebase lag
// returns 10 ** 9 rebase lag factor
function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) {
if (dollars.totalSupply() >= 30000000 * 10 ** 9) {
return 30 * 10 ** 9;
} else {
if (supplyDelta < 0) {
uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15
return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000));
} else {
return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9);
}
}
}
function inRebaseWindow() public view returns (bool) {
return (
now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))
);
}
function computeSupplyDelta(uint256 rate, uint256 targetRate)
private
view
returns (int256)
{
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return dollars.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
// File: contracts/orchestrator.sol
pragma solidity >=0.4.24;
/*
* Orchestrator
*/
contract Orchestrator is Ownable {
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
Transaction[] public transactions;
DollarsPolicy public policy;
constructor(address policy_) public {
Ownable.initialize(msg.sender);
policy = DollarsPolicy(policy_);
}
function rebase()
external
{
require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin
policy.rebase();
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
function addTransaction(address destination, bytes data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
function externalCall(address destination, bytes data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
} | amount in is 10 ** 9 decimals | function burn(uint256 amount)
external
updateAccount(msg.sender)
{
require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
reEntrancyMutex = true;
require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE');
require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
_burn(msg.sender, amount);
reEntrancyMutex = false;
}
| 400,549 | [
1,
8949,
316,
353,
1728,
225,
2468,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
12,
11890,
5034,
3844,
13,
203,
3639,
3903,
203,
3639,
1089,
3032,
12,
3576,
18,
15330,
13,
203,
565,
288,
203,
3639,
2583,
12,
5,
266,
664,
313,
12514,
11433,
16,
315,
862,
17,
2222,
54,
1258,
16068,
611,
57,
8085,
10685,
9722,
4934,
8863,
203,
3639,
283,
664,
313,
12514,
11433,
273,
638,
31,
203,
203,
3639,
2583,
12,
8949,
480,
374,
16,
296,
2192,
51,
5321,
67,
49,
5996,
67,
5948,
67,
7057,
16325,
8284,
203,
3639,
2583,
24899,
17956,
40,
22382,
5913,
15360,
38,
321,
329,
480,
374,
16,
296,
3865,
706,
67,
38,
8521,
67,
49,
5996,
67,
5948,
67,
43,
18857,
67,
22408,
67,
24968,
8284,
203,
3639,
2583,
12,
8949,
1648,
389,
72,
25442,
38,
26488,
63,
3576,
18,
15330,
6487,
296,
706,
6639,
42,
1653,
7266,
2222,
67,
40,
30922,
985,
67,
38,
1013,
4722,
8284,
203,
3639,
2583,
12,
8949,
1648,
389,
17956,
40,
22382,
5913,
15360,
38,
321,
329,
16,
296,
2192,
51,
5321,
67,
49,
5996,
67,
5948,
67,
26005,
67,
22408,
67,
916,
67,
12853,
67,
4296,
67,
862,
19803,
1360,
67,
3865,
706,
55,
8284,
203,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
203,
3639,
283,
664,
313,
12514,
11433,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0xD3E8A594a17f5A57D638a35880632b2a4BE3866F/sources/X.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-_feereceiver 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;
}
}
| 16,692,610 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
67,
3030,
822,
311,
1667,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1772,
288,
203,
203,
2868,
203,
203,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xD74741fe1A35E73048A793a1158b3E3bB3ec98DE/sources/contracts/helloword.sol | Esta funcion permite reemplazar el mensaje almacenado en la variable message | function setMessage(string memory newMessage) public {
message=newMessage;
}
| 14,239,010 | [
1,
9122,
69,
1326,
285,
4641,
1137,
283,
351,
412,
1561,
297,
415,
312,
773,
4365,
73,
524,
5821,
275,
6821,
570,
7125,
2190,
883,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
15227,
12,
1080,
3778,
394,
1079,
13,
1071,
288,
203,
2150,
33,
2704,
1079,
31,
203,
97,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xdf8bFB139AD21Ec238B9e56BeD6f0953202cF104/sources/src/strangers.sol | @dev Emitted when a token points are moved. | event PointsAdded(address caller, address recipient, uint256 amount, uint256 blocktime);
| 17,152,985 | [
1,
1514,
11541,
1347,
279,
1147,
3143,
854,
10456,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
22464,
8602,
12,
2867,
4894,
16,
1758,
8027,
16,
2254,
5034,
3844,
16,
2254,
5034,
1203,
957,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract Owned {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Owned() public{
owner = msg.sender;
}
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
}
contract tokenRecipient {
function receiveApproval (address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract DASABI_IO_Contract is ERC20Token, Owned{
/* Public variables of the token */
string public constant name = "dasabi.io DSBC";
string public constant symbol = "DSBC";
uint256 public constant decimals = 18;
uint256 private constant etherChange = 10**18;
/* Variables of the token */
uint256 public totalSupply;
uint256 public totalRemainSupply;
uint256 public ExchangeRate;
uint256 public CandyRate;
bool public crowdsaleIsOpen;
bool public CandyDropIsOpen;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
mapping (address => bool) public blacklist;
address public multisigAddress;
/* Events */
event mintToken(address indexed _to, uint256 _value);
event burnToken(address indexed _from, uint256 _value);
function () payable public {
require (crowdsaleIsOpen == true);
if (msg.value > 0) {
mintDSBCToken(msg.sender, (msg.value * ExchangeRate * 10**decimals) / etherChange);
}
if(CandyDropIsOpen){
if(!blacklist[msg.sender]){
mintDSBCToken(msg.sender, CandyRate * 10**decimals);
blacklist[msg.sender] = true;
}
}
}
/* Initializes contract and sets restricted addresses */
function DASABI_IO_Contract() public {
owner = msg.sender;
totalSupply = 1000000000 * 10**decimals;
ExchangeRate = 50000;
CandyRate = 50;
totalRemainSupply = totalSupply;
crowdsaleIsOpen = true;
CandyDropIsOpen = true;
}
function setExchangeRate(uint256 _ExchangeRate) public onlyOwner {
ExchangeRate = _ExchangeRate;
}
function crowdsaleOpen(bool _crowdsaleIsOpen) public onlyOwner{
crowdsaleIsOpen = _crowdsaleIsOpen;
}
function CandyDropOpen(bool _CandyDropIsOpen) public onlyOwner{
CandyDropIsOpen = _CandyDropIsOpen;
}
/* Returns total supply of issued tokens */
function totalDistributed() public constant returns (uint256) {
return totalSupply - totalRemainSupply ;
}
/* Returns balance of address */
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/* Transfers tokens from your address to other */
function transfer(address _to, uint256 _value) public returns (bool success) {
require (balances[msg.sender] >= _value); // Throw if sender has insufficient balance
require (balances[_to] + _value > balances[_to]); // Throw if owerflow detected
balances[msg.sender] -= _value; // Deduct senders balance
balances[_to] += _value; // Add recivers blaance
Transfer(msg.sender, _to, _value); // Raise Transfer event
return true;
}
/* Approve other address to spend tokens on your account */
function approve(address _spender, uint256 _value) public returns (bool success) {
allowances[msg.sender][_spender] = _value; // Set allowance
Approval(msg.sender, _spender, _value); // Raise Approval event
return true;
}
/* Approve and then communicate the approved contract in a single tx */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender); // Cast spender to tokenRecipient contract
approve(_spender, _value); // Set approval to contract for _value
spender.receiveApproval(msg.sender, _value, this, _extraData); // Raise method on _spender contract
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (balances[_from] > _value); // Throw if sender does not have enough balance
require (balances[_to] + _value > balances[_to]); // Throw if overflow detected
require (_value <= allowances[_from][msg.sender]); // Throw if you do not have allowance
balances[_from] -= _value; // Deduct senders balance
balances[_to] += _value; // Add recipient blaance
allowances[_from][msg.sender] -= _value; // Deduct allowance for this address
Transfer(_from, _to, _value); // Raise Transfer event
return true;
}
/* Get the amount of allowed tokens to spend */
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
/*withdraw Ether to a multisig address*/
function withdraw(address _multisigAddress) public onlyOwner {
require(_multisigAddress != 0x0);
multisigAddress = _multisigAddress;
multisigAddress.transfer(this.balance);
}
/* Issue new tokens */
function mintDSBCToken(address _to, uint256 _amount) internal {
require (balances[_to] + _amount > balances[_to]); // Check for overflows
require (totalRemainSupply > _amount);
totalRemainSupply -= _amount; // Update total supply
balances[_to] += _amount; // Set minted coins to target
mintToken(_to, _amount); // Create Mint event
Transfer(0x0, _to, _amount); // Create Transfer event from 0x
}
function mintTokens(address _sendTo, uint256 _sendAmount)public onlyOwner {
mintDSBCToken(_sendTo, _sendAmount);
}
/* Destroy tokens from owners account */
function burnTokens(uint256 _amount)public onlyOwner {
require (balances[msg.sender] > _amount); // Throw if you do not have enough balance
totalRemainSupply += _amount; // Deduct totalSupply
balances[msg.sender] -= _amount; // Destroy coins on senders wallet
burnToken(msg.sender, _amount); // Raise Burn event
}
} | Issue new tokens */ | function mintDSBCToken(address _to, uint256 _amount) internal {
require (totalRemainSupply > _amount);
}
| 10,665,623 | [
1,
12956,
394,
2430,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
3948,
38,
1268,
969,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
7010,
3639,
2583,
261,
4963,
1933,
530,
3088,
1283,
405,
389,
8949,
1769,
203,
565,
289,
21281,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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.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";
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 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 "./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.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.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @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 {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath 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 {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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 () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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: MIT
pragma solidity 0.7.5;
import "./IVaultHandler.sol";
import "./Orchestrator.sol";
/**
* @title ERC-20 TCAP Vault
* @author Cryptex.finance
* @notice Contract in charge of handling the TCAP Vault and stake using a Collateral ERC20
*/
contract ERC20VaultHandler is IVaultHandler {
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
)
IVaultHandler(
_orchestrator,
_divisor,
_ratio,
_burnFee,
_liquidationPenalty,
_tcapOracle,
_tcapAddress,
_collateralAddress,
_collateralOracle,
_ethOracle,
_rewardHandler,
_treasury
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "./TCAP.sol";
import "./Orchestrator.sol";
import "./oracles/ChainlinkOracle.sol";
interface IRewardHandler {
function stake(address _staker, uint256 amount) external;
function withdraw(address _staker, uint256 amount) external;
function getRewardFromVault(address _staker) external;
}
/**
* @title TCAP Vault Handler Abstract Contract
* @author Cryptex.Finance
* @notice Contract in charge of handling the TCAP Token and stake
*/
abstract contract IVaultHandler is
Ownable,
AccessControl,
ReentrancyGuard,
Pausable,
IERC165
{
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
using SafeCast for int256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
/**
* @notice Vault object created to manage the mint and burns of TCAP tokens
* @param Id, unique identifier of the vault
* @param Collateral, current collateral on vault
* @param Debt, current amount of TCAP tokens minted
* @param Owner, owner of the vault
*/
struct Vault {
uint256 Id;
uint256 Collateral;
uint256 Debt;
address Owner;
}
/// @notice Vault Id counter
Counters.Counter public counter;
/// @notice TCAP Token Address
TCAP public immutable TCAPToken;
/// @notice Total Market Cap/USD Oracle Address
ChainlinkOracle public immutable tcapOracle;
/// @notice Collateral Token Address
IERC20 public immutable collateralContract;
/// @notice Collateral/USD Oracle Address
ChainlinkOracle public immutable collateralPriceOracle;
/// @notice ETH/USD Oracle Address
ChainlinkOracle public immutable ETHPriceOracle;
/// @notice Value used as divisor with the total market cap, just like the S&P 500 or any major financial index would to define the final tcap token price
uint256 public divisor;
/// @notice Minimun ratio required to prevent liquidation of vault
uint256 public ratio;
/// @notice Fee percentage of the total amount to burn charged on ETH when burning TCAP Tokens
uint256 public burnFee;
/// @notice Penalty charged to vault owner when a vault is liquidated, this value goes to the liquidator
uint256 public liquidationPenalty;
/// @notice Address of the contract that gives rewards to minters of TCAP, rewards are only given if address is set in constructor
IRewardHandler public immutable rewardHandler;
/// @notice Address of the treasury contract (usually the timelock) where the funds generated by the protocol are sent
address public treasury;
/// @notice Owner address to Vault Id
mapping(address => uint256) public userToVault;
/// @notice Id To Vault
mapping(uint256 => Vault) public vaults;
/// @notice value used to multiply chainlink oracle for handling decimals
uint256 public constant oracleDigits = 10000000000;
/// @notice Minimum value that the ratio can be set to
uint256 public constant MIN_RATIO = 150;
/// @notice Maximum value that the burn fee can be set to
uint256 public constant MAX_FEE = 10;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* setRatio.selector ^
* setBurnFee.selector ^
* setLiquidationPenalty.selector ^
* pause.selector ^
* unpause.selector => 0x9e75ab0c
*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when the ratio is updated
event NewRatio(address indexed _owner, uint256 _ratio);
/// @notice An event emitted when the burn fee is updated
event NewBurnFee(address indexed _owner, uint256 _burnFee);
/// @notice An event emitted when the liquidation penalty is updated
event NewLiquidationPenalty(
address indexed _owner,
uint256 _liquidationPenalty
);
/// @notice An event emitted when the treasury contract is updated
event NewTreasury(address indexed _owner, address _tresury);
/// @notice An event emitted when a vault is created
event VaultCreated(address indexed _owner, uint256 indexed _id);
/// @notice An event emitted when collateral is added to a vault
event CollateralAdded(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when collateral is removed from a vault
event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are minted
event TokensMinted(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are burned
event TokensBurned(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when a vault is liquidated
event VaultLiquidated(
uint256 indexed _vaultId,
address indexed _liquidator,
uint256 _liquidationCollateral,
uint256 _reward
);
/// @notice An event emitted when a erc20 token is recovered
event Recovered(address _token, uint256 _amount);
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
) {
require(
_liquidationPenalty.add(100) < _ratio,
"VaultHandler::constructor: liquidation penalty too high"
);
require(
_ratio >= MIN_RATIO,
"VaultHandler::constructor: ratio lower than MIN_RATIO"
);
require(
_burnFee <= MAX_FEE,
"VaultHandler::constructor: burn fee higher than MAX_FEE"
);
divisor = _divisor;
ratio = _ratio;
burnFee = _burnFee;
liquidationPenalty = _liquidationPenalty;
tcapOracle = ChainlinkOracle(_tcapOracle);
collateralContract = IERC20(_collateralAddress);
collateralPriceOracle = ChainlinkOracle(_collateralOracle);
ETHPriceOracle = ChainlinkOracle(_ethOracle);
TCAPToken = _tcapAddress;
rewardHandler = IRewardHandler(_rewardHandler);
treasury = _treasury;
/// @dev counter starts in 1 as 0 is reserved for empty objects
counter.increment();
/// @dev transfer ownership to orchestrator
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if the user hasn't created a vault.
modifier vaultExists() {
require(
userToVault[msg.sender] != 0,
"VaultHandler::vaultExists: no vault created"
);
_;
}
/// @notice Reverts if value is 0.
modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
/**
* @notice Sets the collateral ratio needed to mint tokens
* @param _ratio uint
* @dev Only owner can call it
*/
function setRatio(uint256 _ratio) external virtual onlyOwner {
require(
_ratio >= MIN_RATIO,
"VaultHandler::setRatio: ratio lower than MIN_RATIO"
);
ratio = _ratio;
emit NewRatio(msg.sender, _ratio);
}
/**
* @notice Sets the burn fee percentage an user pays when burning tcap tokens
* @param _burnFee uint
* @dev Only owner can call it
*/
function setBurnFee(uint256 _burnFee) external virtual onlyOwner {
require(
_burnFee <= MAX_FEE,
"VaultHandler::setBurnFee: burn fee higher than MAX_FEE"
);
burnFee = _burnFee;
emit NewBurnFee(msg.sender, _burnFee);
}
/**
* @notice Sets the liquidation penalty % charged on liquidation
* @param _liquidationPenalty uint
* @dev Only owner can call it
* @dev recommended value is between 1-15% and can't be above 100%
*/
function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
/**
* @notice Sets the treasury contract address where fees are transfered to
* @param _treasury address
* @dev Only owner can call it
*/
function setTreasury(address _treasury) external virtual onlyOwner {
require(
_treasury != address(0),
"VaultHandler::setTreasury: not a valid treasury"
);
treasury = _treasury;
emit NewTreasury(msg.sender, _treasury);
}
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
/**
* @notice Allows the owner to Pause the Contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Allows the owner to Unpause the Contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param _tokenAddress address
* @param _tokenAmount uint
* @dev Only owner can call it
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
// Cannot recover the collateral token
require(
_tokenAddress != address(collateralContract),
"Cannot withdraw the collateral tokens"
);
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Allows the safe transfer of ETH
* @param _to account to transfer ETH
* @param _value amount of ETH
*/
function safeTransferETH(address _to, uint256 _value) internal {
(bool success, ) = _to.call{value: _value}(new bytes(0));
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice Returns the Vault information of specified identifier
* @param _id of vault
* @return Id, Collateral, Owner, Debt
*/
function getVault(uint256 _id)
external
view
virtual
returns (
uint256,
uint256,
address,
uint256
)
{
Vault memory vault = vaults[_id];
return (vault.Id, vault.Collateral, vault.Owner, vault.Debt);
}
/**
* @notice Returns the price of the chainlink oracle multiplied by the digits to get 18 decimals format
* @param _oracle to be the price called
* @return price
*/
function getOraclePrice(ChainlinkOracle _oracle)
public
view
virtual
returns (uint256 price)
{
price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits);
}
/**
* @notice Returns the price of the TCAP token
* @return price of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev oracle totalMarketPrice must be in wei format
* @dev P = T / d
* P = TCAP Token Price
* T = Total Crypto Market Cap
* d = Divisor
*/
function TCAPPrice() public view virtual returns (uint256 price) {
uint256 totalMarketPrice = getOraclePrice(tcapOracle);
price = totalMarketPrice.div(divisor);
}
/**
* @notice Returns the minimal required collateral to mint TCAP token
* @param _amount uint amount to mint
* @return collateral of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev C = ((P * A * r) / 100) / cp
* C = Required Collateral
* P = TCAP Token Price
* A = Amount to Mint
* cp = Collateral Price
* r = Minimun Ratio for Liquidation
* Is only divided by 100 as eth price comes in wei to cancel the additional 0s
*/
function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
/**
* @notice Returns the Reward for liquidating a vault
* @param _vaultId of the vault to liquidate
* @return rewardCollateral for liquidating Vault
* @dev the returned value is returned as collateral currency
* @dev R = (LT * (p + 100)) / 100
* R = Liquidation Reward
* LT = Required Liquidation TCAP
* p = liquidation penalty
*/
function liquidationReward(uint256 _vaultId)
public
view
virtual
returns (uint256 rewardCollateral)
{
uint256 req = requiredLiquidationTCAP(_vaultId);
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 reward = (req.mul(liquidationPenalty.add(100)));
rewardCollateral = (reward.mul(tcapPrice)).div(collateralPrice.mul(100));
}
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
/**
* @notice Returns the required fee of ETH to burn the TCAP tokens
* @param _amount to burn
* @return fee
* @dev The returned value is returned in wei
* @dev f = (((P * A * b)/ 100))/ EP
* f = Burn Fee Value
* P = TCAP Token Price
* A = Amount to Burn
* b = Burn Fee %
* EP = ETH Price
*/
function getFee(uint256 _amount) public view virtual returns (uint256 fee) {
uint256 ethPrice = getOraclePrice(ETHPriceOracle);
fee = (TCAPPrice().mul(_amount).mul(burnFee)).div(100).div(ethPrice);
}
/**
* @notice Burns an amount of TCAP Tokens
* @param _vaultId vault id
* @param _amount to burn
*/
function _burn(uint256 _vaultId, uint256 _amount) internal {
Vault storage vault = vaults[_vaultId];
require(
vault.Debt >= _amount,
"VaultHandler::burn: amount greater than debt"
);
vault.Debt = vault.Debt.sub(_amount);
TCAPToken.burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IVaultHandler.sol";
import "./TCAP.sol";
import "./oracles/ChainlinkOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title TCAP Orchestrator
* @author Cryptex.finance
* @notice Orchestrator contract in charge of managing the settings of the vaults, rewards and TCAP token. It acts as the owner of these contracts.
*/
contract Orchestrator is Ownable {
/// @dev Enum which saves the available functions to emergency call.
enum Functions {BURNFEE, LIQUIDATION, PAUSE}
/// @notice Address that can set to 0 the fees or pause the vaults in an emergency event
address public guardian;
/** @dev Interface constants*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/// @dev tracks which vault was emergency called
mapping(IVaultHandler => mapping(Functions => bool)) private emergencyCalled;
/// @notice An event emitted when the guardian is updated
event GuardianSet(address indexed _owner, address guardian);
/// @notice An event emitted when a transaction is executed
event TransactionExecuted(
address indexed target,
uint256 value,
string signature,
bytes data
);
/**
* @notice Constructor
* @param _guardian The guardian address
*/
constructor(address _guardian) {
require(
_guardian != address(0),
"Orchestrator::constructor: guardian can't be zero"
);
guardian = _guardian;
}
/// @notice Throws if called by any account other than the guardian
modifier onlyGuardian() {
require(
msg.sender == guardian,
"Orchestrator::onlyGuardian: caller is not the guardian"
);
_;
}
/**
* @notice Throws if vault is not valid.
* @param _vault address
*/
modifier validVault(IVaultHandler _vault) {
require(
ERC165Checker.supportsInterface(address(_vault), _INTERFACE_ID_IVAULT),
"Orchestrator::validVault: not a valid vault"
);
_;
}
/**
* @notice Throws if TCAP Token is not valid
* @param _tcap address
*/
modifier validTCAP(TCAP _tcap) {
require(
ERC165Checker.supportsInterface(address(_tcap), _INTERFACE_ID_TCAP),
"Orchestrator::validTCAP: not a valid TCAP ERC20"
);
_;
}
/**
* @notice Throws if Chainlink Oracle is not valid
* @param _oracle address
*/
modifier validChainlinkOracle(address _oracle) {
require(
ERC165Checker.supportsInterface(
address(_oracle),
_INTERFACE_ID_CHAINLINK_ORACLE
),
"Orchestrator::validChainlinkOrchestrator: not a valid Chainlink Oracle"
);
_;
}
/**
* @notice Sets the guardian of the orchestrator
* @param _guardian address of the guardian
* @dev Only owner can call it
*/
function setGuardian(address _guardian) external onlyOwner {
require(
_guardian != address(0),
"Orchestrator::setGuardian: guardian can't be zero"
);
guardian = _guardian;
emit GuardianSet(msg.sender, _guardian);
}
/**
* @notice Sets the ratio of a vault
* @param _vault address
* @param _ratio value
* @dev Only owner can call it
*/
function setRatio(IVaultHandler _vault, uint256 _ratio)
external
onlyOwner
validVault(_vault)
{
_vault.setRatio(_ratio);
}
/**
* @notice Sets the burn fee of a vault
* @param _vault address
* @param _burnFee value
* @dev Only owner can call it
*/
function setBurnFee(IVaultHandler _vault, uint256 _burnFee)
external
onlyOwner
validVault(_vault)
{
_vault.setBurnFee(_burnFee);
}
/**
* @notice Sets the burn fee to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyBurnFee(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.BURNFEE] != true,
"Orchestrator::setEmergencyBurnFee: emergency call already used"
);
emergencyCalled[_vault][Functions.BURNFEE] = true;
_vault.setBurnFee(0);
}
/**
* @notice Sets the liquidation penalty of a vault
* @param _vault address
* @param _liquidationPenalty value
* @dev Only owner can call it
*/
function setLiquidationPenalty(
IVaultHandler _vault,
uint256 _liquidationPenalty
) external onlyOwner validVault(_vault) {
_vault.setLiquidationPenalty(_liquidationPenalty);
}
/**
* @notice Sets the liquidation penalty of a vault to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyLiquidationPenalty(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.LIQUIDATION] != true,
"Orchestrator::setEmergencyLiquidationPenalty: emergency call already used"
);
emergencyCalled[_vault][Functions.LIQUIDATION] = true;
_vault.setLiquidationPenalty(0);
}
/**
* @notice Pauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function pauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.PAUSE] != true,
"Orchestrator::pauseVault: emergency call already used"
);
emergencyCalled[_vault][Functions.PAUSE] = true;
_vault.pause();
}
/**
* @notice Unpauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function unpauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
_vault.unpause();
}
/**
* @notice Enables or disables the TCAP Cap
* @param _tcap address
* @param _enable bool
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function enableTCAPCap(TCAP _tcap, bool _enable)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.enableCap(_enable);
}
/**
* @notice Sets the TCAP maximum minting value
* @param _tcap address
* @param _cap uint value
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function setTCAPCap(TCAP _tcap, uint256 _cap)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.setCap(_cap);
}
/**
* @notice Adds Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function addTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.addVaultHandler(address(_vault));
}
/**
* @notice Removes Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function removeTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.removeVaultHandler(address(_vault));
}
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
/**
* @notice Retrieves the eth stuck on the orchestrator
* @param _to address
* @dev Only owner can call it
*/
function retrieveETH(address _to) external onlyOwner {
require(
_to != address(0),
"Orchestrator::retrieveETH: address can't be zero"
);
uint256 amount = address(this).balance;
payable(_to).transfer(amount);
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Orchestrator.sol";
/**
* @title Total Market Cap Token
* @author Cryptex.finance
* @notice ERC20 token on the Ethereum Blockchain that provides total exposure to the cryptocurrency sector.
*/
contract TCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled TCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of TCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn TCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _orchestrator address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Orchestrator _orchestrator
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"TCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints TCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns TCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @title Chainlink Oracle
* @author Cryptex.finance
* @notice Contract in charge or reading the information from a Chainlink Oracle. TCAP contracts read the price directly from this contract. More information can be found on Chainlink Documentation
*/
contract ChainlinkOracle is Ownable, IERC165 {
AggregatorV3Interface internal aggregatorContract;
/*
* setReferenceContract.selector ^
* getLatestAnswer.selector ^
* getLatestTimestamp.selector ^
* getPreviousAnswer.selector ^
* getPreviousTimestamp.selector => 0x85be402b
*/
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @notice Called once the contract is deployed.
* Set the Chainlink Oracle as an aggregator.
*/
constructor(address _aggregator, address _timelock) {
require(_aggregator != address(0) && _timelock != address(0), "address can't be 0");
aggregatorContract = AggregatorV3Interface(_aggregator);
transferOwnership(_timelock);
}
/**
* @notice Changes the reference contract.
* @dev Only owner can call it.
*/
function setReferenceContract(address _aggregator) public onlyOwner() {
aggregatorContract = AggregatorV3Interface(_aggregator);
}
/**
* @notice Returns the latest answer from the reference contract.
* @return price
*/
function getLatestAnswer() public view returns (int256) {
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
require(
timeStamp != 0,
"ChainlinkOracle::getLatestAnswer: round is not complete"
);
require(
answeredInRound >= roundID,
"ChainlinkOracle::getLatestAnswer: stale data"
);
return price;
}
/**
* @notice Returns the latest round from the reference contract.
*/
function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns a given round from the reference contract.
* @param _id of round
*/
function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.getRoundData(_id);
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns the last time the Oracle was updated.
*/
function getLatestTimestamp() public view returns (uint256) {
(, , , uint256 timeStamp, ) = aggregatorContract.latestRoundData();
return timeStamp;
}
/**
* @notice Returns a previous answer updated on the Oracle.
* @param _id of round
* @return price
*/
function getPreviousAnswer(uint80 _id) public view returns (int256) {
(uint80 roundID, int256 price, , , ) = aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousAnswer: not enough history"
);
return price;
}
/**
* @notice Returns a previous time the Oracle was updated.
* @param _id of round
* @return timeStamp
*/
function getPreviousTimestamp(uint80 _id) public view returns (uint256) {
(uint80 roundID, , , uint256 timeStamp, ) =
aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousTimestamp: not enough history"
);
return timeStamp;
}
/**
* @notice ERC165 Standard for support of interfaces.
*/
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return (interfaceId == _INTERFACE_ID_CHAINLINK_ORACLE ||
interfaceId == _INTERFACE_ID_ERC165);
}
} | * @notice Sets maximum value the total supply of TCAP can have @param _cap value @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity. @dev Only owner can call it/ | function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
| 172,418 | [
1,
2785,
4207,
460,
326,
2078,
14467,
434,
399,
17296,
848,
1240,
225,
389,
5909,
460,
225,
5203,
3523,
1526,
353,
638,
16,
312,
474,
353,
486,
2935,
358,
5672,
2430,
716,
4102,
10929,
326,
2078,
14467,
5721,
578,
3959,
326,
1269,
7519,
18,
225,
5098,
3410,
848,
745,
518,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
4664,
12,
11890,
5034,
389,
5909,
13,
3903,
1338,
5541,
288,
203,
565,
3523,
273,
389,
5909,
31,
203,
565,
3626,
1166,
4664,
12,
3576,
18,
15330,
16,
389,
5909,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// version: 0.1
pragma solidity ^0.8.9;
library SM2Curve {
event Log(string, uint);
uint constant SM2_P = 0xfffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff;
uint constant SM2_A = 0xfffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc;
uint constant SM2_B = 0x28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93;
uint constant SM2_X = 0x32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7;
uint constant SM2_Y = 0xbc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0;
uint constant SM2_N = 0xfffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123;
uint constant SM2_U = (SM2_P - 3)/4 + 1;
function submod(uint a, uint b, uint p) internal pure returns (uint) {
if (a >= b) {
return a - b;
} else {
return ((p - b) + a);
}
}
// a/2 == (a + p)/2 == (a + 1)/2 + (p - 1)/2
// FIXME: change add() formula with out div2 operation
function div2mod(uint a, uint p) internal pure returns (uint) {
if (a % 2 == 0) {
return a/2;
} else {
return ((a + 1)/2) + (p - 1)/2;
}
}
function expmod(uint a, uint e, uint m) internal pure returns (uint) {
uint r = 1;
while (e > 0) {
if (e & 1 == 1) {
r = mulmod(r, a, m);
}
a = mulmod(a, a, m);
e >>= 1;
}
return r;
}
function invmod(uint a, uint p) internal pure returns (uint) {
return expmod(a, p-2, p);
}
function invmodp(uint a) internal pure returns (uint) {
uint r;
uint a1;
uint a2;
uint a3;
uint a4;
uint a5;
int i;
a1 = mulmod(a, a, SM2_P);
a2 = mulmod(a1, a, SM2_P);
a3 = mulmod(a2, a2, SM2_P);
a3 = mulmod(a3, a3, SM2_P);
a3 = mulmod(a3, a2, SM2_P);
a4 = mulmod(a3, a3, SM2_P);
a4 = mulmod(a4, a4, SM2_P);
a4 = mulmod(a4, a4, SM2_P);
a4 = mulmod(a4, a4, SM2_P);
a4 = mulmod(a4, a3, SM2_P);
a5 = mulmod(a4, a4, SM2_P);
for (i = 1; i < 8; i++)
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a4, SM2_P);
for (i = 0; i < 8; i++)
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a4, SM2_P);
for (i = 0; i < 4; i++)
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a3, SM2_P);
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a2, SM2_P);
a5 = mulmod(a5, a5, SM2_P);
a5 = mulmod(a5, a, SM2_P);
a4 = mulmod(a5, a5, SM2_P);
a3 = mulmod(a4, a1, SM2_P);
a5 = mulmod(a4, a4, SM2_P);
for (i = 1; i< 31; i++)
a5 = mulmod(a5, a5, SM2_P);
a4 = mulmod(a5, a4, SM2_P);
a4 = mulmod(a4, a4, SM2_P);
a4 = mulmod(a4, a, SM2_P);
a3 = mulmod(a4, a2, SM2_P);
for (i = 0; i < 33; i++)
a5 = mulmod(a5, a5, SM2_P);
a2 = mulmod(a5, a3, SM2_P);
a3 = mulmod(a2, a3, SM2_P);
for (i = 0; i < 32; i++)
a5 = mulmod(a5, a5, SM2_P);
a2 = mulmod(a5, a3, SM2_P);
a3 = mulmod(a2, a3, SM2_P);
a4 = mulmod(a2, a4, SM2_P);
for (i = 0; i < 32; i++)
a5 = mulmod(a5, a5, SM2_P);
a2 = mulmod(a5, a3, SM2_P);
a3 = mulmod(a2, a3, SM2_P);
a4 = mulmod(a2, a4, SM2_P);
for (i = 0; i < 32; i++)
a5 = mulmod(a5, a5, SM2_P);
a2 = mulmod(a5, a3, SM2_P);
a3 = mulmod(a2, a3, SM2_P);
a4 = mulmod(a2, a4, SM2_P);
for (i = 0; i < 32; i++)
a5 = mulmod(a5, a5, SM2_P);
a2 = mulmod(a5, a3, SM2_P);
a3 = mulmod(a2, a3, SM2_P);
a4 = mulmod(a2, a4, SM2_P);
for (i = 0; i < 32; i++)
a5 = mulmod(a5, a5, SM2_P);
r = mulmod(a4, a5, SM2_P);
return r;
}
struct SM2Point {
uint X;
uint Y;
uint Z;
}
function isOnCurve(SM2Point memory P) public returns (bool) {
uint t0;
uint t1;
uint t2;
if (P.Z == 1) {
t0 = mulmod(P.Y, P.Y, SM2_P);
t1 = mulmod(P.X, 3, SM2_P);
t0 = addmod(t0, t1, SM2_P);
t1 = mulmod(P.X, P.X, SM2_P);
t1 = mulmod(t1, P.X, SM2_P);
t1 = addmod(t1, SM2_B, SM2_P);
} else {
t0 = mulmod(P.Y, P.Y, SM2_P);
t1 = mulmod(P.Z, P.Z, SM2_P);
t2 = mulmod(t1, t1, SM2_P);
t1 = mulmod(t1, t2, SM2_P);
t1 = mulmod(t1, SM2_B, SM2_P);
t2 = mulmod(t2, P.X, SM2_P);
t2 = mulmod(t2, 3, SM2_P);
t0 = addmod(t0, t2, SM2_P);
t2 = mulmod(P.X, P.X, SM2_P);
t2 = mulmod(t2, P.X, SM2_P);
t1 = addmod(t1, t2, SM2_P);
}
//emit Log("t0", t0);
//emit Log("t1", t1);
return (t0 == t1);
}
function neg(SM2Point memory P) public pure returns (SM2Point memory) {
return SM2Point(P.X, SM2_P - P.Y, P.Z);
}
function dbl(SM2Point memory P) public returns (SM2Point memory) {
uint X1 = P.X;
uint Y1 = P.Y;
uint Z1 = P.Z;
//emit Log("X1", X1);
uint T1;
uint T2;
uint T3;
uint X3;
uint Y3;
uint Z3;
T1 = mulmod(Z1, Z1, SM2_P);
T2 = submod(X1, T1, SM2_P); //emit Log("T2 = X1 - T1 = ", T2);
T1 = addmod(X1, T1, SM2_P); //emit Log("T1 = X1 + T1 = ", T1);
T2 = mulmod(T2, T1, SM2_P); //emit Log("T2 = T2 * T1 = ", T2);
T2 = mulmod(3, T2, SM2_P); //emit Log("T2 = 3 * T2 = ", T2);
Y3 = addmod(Y1, Y1, SM2_P); //emit Log("Y3 = 2 * Y1 = ", Y3);
Z3 = mulmod(Y3, Z1, SM2_P); //emit Log("Z3 = Y3 * Z1 = ", Z3);
Y3 = mulmod(Y3, Y3, SM2_P); //emit Log("Y3 = Y3^2 = ", Y3);
T3 = mulmod(Y3, X1, SM2_P); //emit Log("T3 = Y3 * X1 = ", T3);
Y3 = mulmod(Y3, Y3, SM2_P); //emit Log("Y3 = Y3^2 = ", Y3);
Y3 = div2mod(Y3, SM2_P); //emit Log("Y3 = Y3/2 = ", Y3);
X3 = mulmod(T2, T2, SM2_P); //emit Log("X3 = T2^2 = ", X3);
T1 = addmod(T3, T3, SM2_P); //emit Log("T1 = 2 * T1 = ", T1);
X3 = submod(X3, T1, SM2_P); //emit Log("X3 = X3 - T1 = ", X3);
T1 = submod(T3, X3, SM2_P); //emit Log("T1 = T3 - X3 = ", T1);
T1 = mulmod(T1, T2, SM2_P); //emit Log("T1 = T1 * T2 = ", T1);
Y3 = submod(T1, Y3, SM2_P); //emit Log("Y3 = T1 - Y3 = ", Y3);
return SM2Point(X3, Y3, Z3);
}
function isAtInfinity(SM2Point memory P) public returns (bool) {
//emit Log("Z1", P.Z);
return (P.Z == 0);
}
function add(SM2Point memory P, SM2Point memory Q) public returns (SM2Point memory) {
uint X1 = P.X;
uint Y1 = P.Y;
uint Z1 = P.Z;
uint x2 = Q.X;
uint y2 = Q.Y;
uint T1;
uint T2;
uint T3;
uint T4;
uint X3;
uint Y3;
uint Z3;
//emit Log("Z1", P.Z);
if (isAtInfinity(Q)) {
return P;
}
if (isAtInfinity(P)) {
return Q;
}
assert(Q.Z == 1);
T1 = mulmod(Z1, Z1, SM2_P);
T2 = mulmod(T1, Z1, SM2_P);
T1 = mulmod(T1, x2, SM2_P);
T2 = mulmod(T2, y2, SM2_P);
T1 = submod(T1, X1, SM2_P);
T2 = submod(T2, Y1, SM2_P);
if (T1 == 0) {
if (T2 == 0) {
return dbl(Q);
} else {
return SM2Point(1, 1, 0);
}
}
Z3 = mulmod(Z1, T1, SM2_P);
T3 = mulmod(T1, T1, SM2_P);
T4 = mulmod(T3, T1, SM2_P);
T3 = mulmod(T3, X1, SM2_P);
T1 = addmod(T3, T3, SM2_P);
X3 = mulmod(T2, T2, SM2_P);
X3 = submod(X3, T1, SM2_P);
X3 = submod(X3, T4, SM2_P);
T3 = submod(T3, X3, SM2_P);
T3 = mulmod(T3, T2, SM2_P);
T4 = mulmod(T4, Y1, SM2_P);
Y3 = submod(T3, T4, SM2_P);
return SM2Point(X3, Y3, Z3);
}
function scalarMul(uint k, SM2Point memory P) public returns (SM2Point memory) {
SM2Point memory Q = SM2Point(1, 1, 0);
//emit Log("k", k);
for (uint i = 0; i < 256; i++) {
Q = dbl(Q);
if ((k & 0x8000000000000000000000000000000000000000000000000000000000000000) > 0) {
Q = add(Q, P);
}
k <<= 1;
}
return Q;
}
function scalarMulGenerator(uint k) public returns (SM2Point memory) {
SM2Point memory G = SM2Point(SM2_X, SM2_Y, 1);
return scalarMul(k, G);
}
/*
* sm2sign:
* (x1, y1) = k*G
* v = y1 mod 2
* e = SM3(Z||M) in [0, 2^256-1]
* r = (e + x1) mod n
* s = (k - r*d) * (d + 1)^-1 (mod n)
*
* sm2recover:
* d = (s + r)^-1 * (k - s) (mod n)
* P = d*G = (s + r)^-1 * (k*G - s*G)
* = (s + r)^-1 * (Q - s*G)
* = -(s + r)^-1 * (s*G - Q)
*
* (x1, y1) from r:
* // r = (e + x1) mod n
* // x1 \equiv (r - e) (mod n)
* x1 = (r - e) mod n if restrict x1 in [1, n-1]
* g = x1^3 + a*x1 + b (mod p)
* u = (p - 3)/4 + 1
* y1 = g^u (mod p), check y1^2 == g (mod p)
* if (y1 % 2 != v)
y1 = p - y1
*/
function sm2recover(bytes32 hash, uint8 _v, bytes32 _r, bytes32 _s) public returns (address) {
uint r = uint(_r);
uint s = uint(_s);
uint e = uint(hash);
uint8 v = _v - 27;
uint x;
uint y;
uint z;
uint g;
x = submod(r, e, SM2_N);
g = mulmod(x, x, SM2_P);
g = addmod(g, SM2_A, SM2_P);
g = mulmod(g, x, SM2_P);
g = addmod(g, SM2_B, SM2_P);
y = expmod(g, SM2_U, SM2_P);
if (mulmod(y, y, SM2_P) != g) {
return address(0x0);
}
if (y & 1 != v) {
y = SM2_P - y;
}
// -Q = (x, -y)
SM2Point memory Q = SM2Point(x, SM2_P - y, 1);
// g = -(s + r)^-1 (mod n)
g = addmod(s, r, SM2_N);
g = invmod(g, SM2_N);
g = SM2_N - g;
SM2Point memory P = scalarMulGenerator(s);
P = add(P, Q);
x = P.X;
y = P.Y;
z = P.Z;
z = invmod(z, SM2_P);
y = mulmod(y, z, SM2_P);
z = mulmod(z, z, SM2_P);
x = mulmod(x, z, SM2_P);
y = mulmod(y, z, SM2_P);
P = scalarMul(g, SM2Point(x, y, 1));
// (x, y) = (X/Z^2, Y/Z^3)
x = P.X;
y = P.Y;
z = P.Z;
z = invmod(z, SM2_P);
y = mulmod(y, z, SM2_P);
z = mulmod(z, z, SM2_P);
x = mulmod(x, z, SM2_P);
y = mulmod(y, z, SM2_P);
// generate ethereum address generation
// replace keccake256 to sm3 in the future
return address(uint160(uint256(keccak256(abi.encodePacked(x, y)))));
}
function sm2verify(bytes32 hash, bytes memory sig) public returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return address(0x0);
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := add(mload(add(sig, 65)), 255)
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28 && v != 37 && v != 38) {
return address(0x0);
}
return sm2recover(hash, v, r, s);
}
function isEqual(SM2Point memory P, SM2Point memory Q) public returns (bool) {
return isAtInfinity(add(P, neg(Q)));
}
function genSig(uint256 x, uint256 y, uint8 v) public returns (bytes memory) {
bytes memory res = new bytes(65);
assembly {
mstore(add(res, 32), x)
mstore(add(res, 64), y)
mstore8(add(res, 96), v)
}
return res;
}
function genHash(uint256 x) public returns (bytes32) {
return bytes32(x);
}
function testField() public returns (bool) {
SM2Point memory G = SM2Point(SM2_X, SM2_Y, 1);
assert(isOnCurve(G));
uint r = 0x4aab6dac98f774bf8268269d5177dab84e5e82bb4323d768f7117cc3bf3b6189;
uint s = 0xe9b330ab81228432961ce806b4ab6898ddc512cc863836e068c627c1e97e91c2;
uint r_sub_s = submod(r, s, SM2_P);
uint r_div2 = div2mod(r, SM2_P);
uint r_exp_s = expmod(r, s, SM2_P);
uint r_inv = invmod(r, SM2_P);
uint r_invp = invmodp(r);
assert(r_sub_s == 0x60f83d0017d4f08cec4b3e969ccc721f70996fedbceba0898e4b5501d5bccfc6);
assert(r_div2 == 0xa555b6d5cc7bba5fc134134ea8bbed5c272f415d2191ebb4fb88be61df9db0c4);
assert(r_exp_s == 0xc3aac2154d0a9c952cd53a7d52266833da40d18692f378f1cadfe00690b0b0bd);
assert(r_inv == 0xee295df6b7c057c079ee6a7a9c8dfa8f84f4debed40fcf0d6aa4f38337bba10d);
assert(r_invp == 0xee295df6b7c057c079ee6a7a9c8dfa8f84f4debed40fcf0d6aa4f38337bba10d);
return true;
}
function testPoint() public returns (bool) {
SM2Point memory R = SM2Point(0x8061401c4f5626681f94f46bb956b879535a1ce4c84053b9aa5f84665041a980, 0xf30ff6d94d44360d13863b9bac32a7c4eb4897144d09b6663a67fe2b4b68a4a0, 1);
SM2Point memory S = SM2Point(0x9619582757fd0fcea01cc42d654b90cc113e4d3527113ddc655278880de57c89, 0x8722774b08e5e0ccc4f959fcadf6bb57e32eb905404e510aa8d549babc7c0baa, 1);
assert(isOnCurve(R));
assert(isOnCurve(S));
uint k = 0xd3aae3f7ba923334977bb7b0af0029fe521af20db2127df12ff2d25be127a661;
SM2Point memory nR = scalarMul(SM2_N, R);
SM2Point memory negR = neg(R);
SM2Point memory dblR = dbl(R);
SM2Point memory R_add_S = add(R, S);
SM2Point memory R_sub_S = add(R, neg(S));
SM2Point memory kR = scalarMul(k, R);
SM2Point memory kG = scalarMulGenerator(k);
assert(isAtInfinity(nR));
assert(isEqual(negR, SM2Point(0x8061401c4f5626681f94f46bb956b879535a1ce4c84053b9aa5f84665041a980, 0xcf00925b2bbc9f2ec79c46453cd583b14b768eab2f6499ac59801d4b4975b5f, 1)));
assert(isEqual(dblR, SM2Point(0x223f44ae3762f2c3127c325fd0c613f84476e3f0824d2d0dc7dd2a7fb7af371f, 0xc968f53708f0a7e3618c7ef3a4c038f771e9516a2525d55edd87695d9017fc10, 1)));
assert(isEqual(R_add_S, SM2Point(0xd74c24475d39bbc3ddc454bb59ea1bddb0a1e38e418e5afd2e4ce5975780bf11, 0x3147de9be2fb1a27424af4d074e2d6e73402db6e071a10f5422f5567580e0795, 1)));
assert(isEqual(R_sub_S, SM2Point(0x5cd18bbc4a9cccb484df3870f216bd6757b92dd03f71f711033bc11619481df0, 0x10536bc6ed2044700b193edc32c5a54c6a534cffc4786c8d1f56474af3e59fb5, 1)));
assert(isEqual(kR, SM2Point(0xf0ef06241fa581922dc1fcdffa9e8468bbc530cd3bda0e2fd774a84f93bbd6e2, 0x2911d25c8a99ca5f9adab0eca566f2bfaa01f932b1bf59c02f1c5aa3e69d9755, 1)));
assert(isEqual(kG, SM2Point(0x3335cafb1a0205a320afdb354a76954bced810863739aaf49fbba5f1fa825634, 0x100e83c4af1082f11ad8823b2f1e8e98ac9f3c2f8b602190bc492675aef091b5, 1)));
return true;
}
function testSign() public returns (bool) {
// bytes memory sig = genSig(0x7eaae95db44c417c1d3f0e24f911a029beae982e8f617bfefc69ca39e9866fd6, 0x2dc9efce73d232a549b2fdd1870eb4df7e62a8196cf2862749337627a3d4dfd7, 2);
// bytes32 hash = genHash(0x4b751e629a4a3bd8fc8f32efae9b0addefd687a85827d10a5cae2447ef0419a2);
// address res = sm2verify(hash, sig);
// emit Log("res", res);
return true;
}
}
contract sm2_test {
function test() public returns (bool) {
SM2Curve.testField();
SM2Curve.testPoint();
// SM2Curve.testSign();
return true;
}
}
| g = -(s + r)^-1 (mod n) | g = addmod(s, r, SM2_N);
| 6,428,203 | [
1,
75,
273,
300,
12,
87,
397,
436,
13,
66,
17,
21,
261,
1711,
290,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
75,
273,
527,
1711,
12,
87,
16,
436,
16,
12014,
22,
67,
50,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.15;
contract IAugur {
function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING
function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING
function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING
function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING
function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING
function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING
function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING
function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING
function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING
function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IOwnable {
function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING
}
contract ITyped {
function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING
}
library SafeMathUint256 {
function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
return a - b;
}
function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a <= b) {
return a;
} else {
return b;
}
}
function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a >= b) {
return a;
} else {
return b;
}
}
function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING
return 0;
}
function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING
return a % b == 0;
}
// Float [fixed point] Operations
function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, b), base);
}
function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, base), b);
}
}
interface IERC1155 {
event TRANSFERSINGLE49( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TRANSFERBATCH882( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event APPROVALFORALL731( //inject NONSTANDARD NAMING
address indexed owner,
address indexed operator,
bool approved
);
event URI998( //inject NONSTANDARD NAMING
string value,
uint256 indexed id
);
function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFBATCH918( //inject NONSTANDARD NAMING
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
// solhint-disable-next-line no-simple-event-func-name
event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_account];
}
function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(msg.sender, _recipient, _amount);
return true;
}
function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowances[_owner][_spender];
}
function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, _amount);
return true;
}
function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(_sender, _recipient, _amount);
_APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount));
return true;
}
function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue));
return true;
}
function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue));
return true;
}
function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
balances[_sender] = balances[_sender].SUB692(_amount);
balances[_recipient] = balances[_recipient].ADD571(_amount);
emit TRANSFER723(_sender, _recipient, _amount);
ONTOKENTRANSFER292(_sender, _recipient, _amount);
}
function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.ADD571(_amount);
balances[_account] = balances[_account].ADD571(_amount);
emit TRANSFER723(address(0), _account, _amount);
}
function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].SUB692(_amount);
totalSupply = totalSupply.SUB692(_amount);
emit TRANSFER723(_account, address(0), _amount);
}
function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit APPROVAL665(_owner, _spender, _amount);
}
function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
_BURN356(_account, _amount);
_APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING
}
contract VariableSupplyToken is ERC20 {
using SafeMathUint256 for uint256;
function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_MINT880(_target, _amount);
ONMINT315(_target, _amount);
return true;
}
function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_BURN356(_target, _amount);
ONBURN653(_target, _amount);
return true;
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING
}
}
contract IAffiliateValidator {
function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IDisputeWindow is ITyped, IERC20 {
function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING
function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING
function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING
function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING
function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING
function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING
function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING
function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING
function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING
function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING
function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING
function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING
function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING
function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING
function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IReportingParticipant {
function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING
function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING
function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING
function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 {
function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING
function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING
function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING
function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING
function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING
function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING
function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING
function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING
function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING
function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING
function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING
}
contract IReputationToken is IERC20 {
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING
}
contract IShareToken is ITyped, IERC1155 {
function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING
function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING
function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING
function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING
function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING
function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING
function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING
function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING
function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING
function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IUniverse {
function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING
function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING
function FORK341() public returns (bool); //inject NONSTANDARD NAMING
function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING
function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING
function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING
function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING
function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING
function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING
function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING
}
contract IV2ReputationToken is IReputationToken {
function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING
}
library Reporting {
uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING
uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING
uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING
uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING
uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING
uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING
uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING
uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING
uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING
uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING
uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING
uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING
uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING
uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING
uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING
uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING
uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING
uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING
function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING
function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING
function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING
function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING
function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING
function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING
function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING
function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING
function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING
function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING
function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING
function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING
function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING
function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING
function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING
function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING
function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING
function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING
}
contract IAugurTrading {
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING
}
contract IOrders {
function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING
function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING
function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING
function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING
function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING
function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING
function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING
function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING
function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING
function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING
function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING
function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING
require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.LOOKUP594("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING
GETORDERID157(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP992( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING
function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM81(address to) external; //inject NONSTANDARD NAMING
function SYNC86() external; //inject NONSTANDARD NAMING
function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING
}
contract IRepSymbol {
function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract ReputationToken is VariableSupplyToken, IV2ReputationToken {
using SafeMathUint256 for uint256;
string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING
IUniverse internal universe;
IUniverse public parentUniverse;
uint256 internal totalMigrated;
IERC20 public legacyRepToken;
IAugur public augur;
address public warpSync;
constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public {
augur = _augur;
universe = _universe;
parentUniverse = _parentUniverse;
warpSync = _augur.LOOKUP594("WarpSync");
legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken"));
require(warpSync != address(0));
require(legacyRepToken != IERC20(0));
}
function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING
return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe));
}
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(_attotokens > 0);
IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators);
IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35();
BURN234(msg.sender, _attotokens);
_destination.MIGRATEIN692(msg.sender, _attotokens);
return true;
}
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
IUniverse _parentUniverse = parentUniverse;
require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35());
require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510());
MINT146(_reporter, _attotokens);
totalMigrated += _attotokens;
// Update the fork tentative winner and finalize if we can
if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) {
_parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230());
}
return true;
}
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING
IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender);
require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant));
// simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute
uint256 _bonus = _amountMigrated.MUL760(2) / 5;
MINT146(address(_reportingParticipant), _bonus);
return true;
}
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING
require(warpSync == msg.sender);
MINT146(_target, _amountToMint);
universe.UPDATEFORKVALUES73();
return true;
}
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
BURN234(msg.sender, _amountToBurn);
return true;
}
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(IUniverse(msg.sender) == universe);
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING
IUniverse _universe = _shadyReputationToken.GETUNIVERSE719();
require(universe.ISPARENTOF319(_universe));
require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken);
}
function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING
return universe;
}
function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalMigrated;
}
function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING
return legacyRepToken;
}
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _totalSupply = totalSupply;
if (parentUniverse == IUniverse(0)) {
return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0)));
} else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) {
return _totalSupply;
} else {
return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552();
}
}
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]);
}
function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]);
}
function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING
require(parentUniverse == IUniverse(0));
uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender);
require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance));
MINT146(msg.sender, _legacyBalance);
return true;
}
} | inject NONSTANDARD NAMING
| function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { | 2,554,174 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
490,
3047,
24062,
11249,
19384,
2226,
61,
862,
4762,
2689,
8412,
29,
2643,
1435,
1071,
1135,
261,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xd6d5bA891D50f9B4EB66837Adb58A83D6A5361D5/sources/contracts/campaigns/Campaigns.sol | @notice Total claim fees accrued that is withdrawable | uint256 public totalClaimFees;
| 16,188,893 | [
1,
5269,
7516,
1656,
281,
4078,
86,
5957,
716,
353,
598,
9446,
429,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
2078,
9762,
2954,
281,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/**
* @notice Solidity library offering basic trigonometry functions where inputs and outputs are
* integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18.
*
* This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas
* which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol
*
* Compared to Lefteris' implementation, this version makes the following changes:
* - Uses a 32 bits instead of 16 bits for improved accuracy
* - Updated for Solidity 0.8.x
* - Various gas optimizations
* - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the
* integer format used by the algorithm
*
* Lefertis' implementation is based off Dave Dribin's trigint C library
* http://www.dribin.org/dave/trigint/
*
* Which in turn is based from a now deleted article which can be found in the Wayback Machine:
* http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html
*/
pragma solidity ^0.8.7;
library Trigonometry {
// Table index into the trigonometric table
uint256 constant INDEX_WIDTH = 8;
// Interpolation between successive entries in the table
uint256 constant INTERP_WIDTH = 16;
uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH;
uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH;
uint32 constant ANGLES_IN_CYCLE = 1073741824;
uint32 constant QUADRANT_HIGH_MASK = 536870912;
uint32 constant QUADRANT_LOW_MASK = 268435456;
uint256 constant SINE_TABLE_SIZE = 256;
// Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for
// interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/
uint256 constant PI = 3141592653589793238;
uint256 constant TWO_PI = 2 * PI;
uint256 constant PI_OVER_TWO = PI / 2;
// Constant sine lookup table generated by generate_trigonometry.py. We must use a constant
// bytes array because constant arrays are not supported in Solidity
uint8 constant entry_bytes = 4;
bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff";
/**
* @notice Return the sine of a value, specified in radians scaled by 1e18
* @dev This algorithm for converting sine only uses integer values, and it works by dividing the
* circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the
* standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to
* 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard
* range of -1 to 1, again scaled by 1e18
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
// Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range
// of 0 to 1,073,741,824
_angle = ANGLES_IN_CYCLE * (_angle % TWO_PI) / 2 / PI;
// Apply a mask on an integer to extract a certain number of bits, where angle is the integer
// whose bits we want to get, the width is the width of the bits (in bits) we want to extract,
// and the offset is the offset of the bits (in bits) we want to extract. The result is an
// integer containing _width bits of _value starting at the offset bit
uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
// The lookup table only contains data for one quadrant (since sin is symmetric around both
// axes), so here we figure out which quadrant we're in, then we lookup the values in the
// table then modify values accordingly
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
// Index into the lookup table and returns the values at indices `index` and `index + 1`
bytes memory table = sin_table;
uint256 offset1 = (index + 1) * entry_bytes;
uint256 offset2 = (index + 2) * entry_bytes;
uint32 x1; assembly { x1 := mload(add(table, offset1)) }
uint32 x2; assembly { x2 := mload(add(table, offset2)) }
// Approximate angle by interpolating in the table, accounting for the quadrant
uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH;
int256 sine = is_odd_quadrant ? int256(uint256(x1)) + int256(approximation) : int256(uint256(x2)) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
// Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18.
// This can never overflow because sine is bounded by the above values
return sine * 1e18 / 2_147_483_647;
}
}
/**
* @notice Return the cosine of a value, specified in radians scaled by 1e18
* @dev This is identical to the sin() method, and just computes the value by delegating to the
* sin() method using the identity cos(x) = sin(x + pi/2)
* @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function cos(uint256 _angle) internal pure returns (int256) {
unchecked {
return sin(_angle + PI_OVER_TWO);
}
}
}
| * @notice Return the sine of a value, specified in radians scaled by 1e18 @dev This algorithm for converting sine only uses integer values, and it works by dividing the circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard range of -1 to 1, again scaled by 1e18 @param _angle Angle to convert @return Result scaled by 1e18/ Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range of 0 to 1,073,741,824 Apply a mask on an integer to extract a certain number of bits, where angle is the integer whose bits we want to get, the width is the width of the bits (in bits) we want to extract, and the offset is the offset of the bits (in bits) we want to extract. The result is an integer containing _width bits of _value starting at the offset bit The lookup table only contains data for one quadrant (since sin is symmetric around both axes), so here we figure out which quadrant we're in, then we lookup the values in the table then modify values accordingly | function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = ANGLES_IN_CYCLE * (_angle % TWO_PI) / 2 / PI;
uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
uint256 offset1 = (index + 1) * entry_bytes;
uint256 offset2 = (index + 2) * entry_bytes;
int256 sine = is_odd_quadrant ? int256(uint256(x1)) + int256(approximation) : int256(uint256(x2)) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
| 12,684,521 | [
1,
990,
326,
272,
558,
434,
279,
460,
16,
1269,
316,
13703,
12304,
635,
404,
73,
2643,
225,
1220,
4886,
364,
14540,
272,
558,
1338,
4692,
3571,
924,
16,
471,
518,
6330,
635,
3739,
10415,
326,
12470,
1368,
5196,
2831,
15479,
16,
277,
18,
73,
18,
1915,
854,
404,
16,
8642,
23,
16,
5608,
21,
16,
28,
3247,
261,
22,
66,
5082,
13,
5291,
4971,
16,
3560,
434,
326,
4529,
12360,
10904,
261,
22,
7259,
13703,
2934,
6338,
1915,
16,
732,
336,
392,
876,
316,
1048,
300,
22,
16,
29488,
16,
8875,
23,
16,
30792,
358,
576,
16,
29488,
16,
8875,
23,
16,
30792,
16,
261,
12784,
353,
326,
943,
460,
434,
392,
509,
1578,
13,
1492,
353,
1508,
5970,
1473,
358,
326,
4529,
1048,
434,
300,
21,
358,
404,
16,
3382,
12304,
635,
404,
73,
2643,
225,
389,
4341,
24154,
358,
1765,
327,
3438,
12304,
635,
404,
73,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
5367,
12,
11890,
5034,
389,
4341,
13,
2713,
16618,
1135,
261,
474,
5034,
13,
288,
203,
565,
22893,
288,
203,
1377,
389,
4341,
273,
432,
4960,
11386,
67,
706,
67,
16068,
23181,
380,
261,
67,
4341,
738,
24722,
51,
67,
1102,
13,
342,
576,
342,
7024,
31,
203,
203,
1377,
2254,
5034,
8174,
273,
261,
67,
4341,
1671,
11391,
52,
67,
11271,
13,
473,
14015,
21,
2296,
11391,
52,
67,
10023,
13,
300,
404,
1769,
203,
1377,
2254,
5034,
770,
225,
273,
261,
67,
4341,
1671,
12425,
67,
11271,
13,
225,
473,
14015,
21,
2296,
12425,
67,
10023,
13,
225,
300,
404,
1769,
203,
203,
1377,
1426,
353,
67,
31755,
67,
21733,
6890,
1377,
273,
261,
67,
4341,
473,
10110,
1880,
54,
6856,
67,
4130,
67,
11704,
13,
225,
422,
374,
31,
203,
1377,
1426,
353,
67,
13258,
67,
21733,
6890,
273,
261,
67,
4341,
473,
10110,
1880,
54,
6856,
67,
29996,
67,
11704,
13,
480,
374,
31,
203,
203,
1377,
309,
16051,
291,
67,
31755,
67,
21733,
6890,
13,
288,
203,
3639,
770,
273,
348,
3740,
67,
7775,
67,
4574,
300,
404,
300,
770,
31,
203,
1377,
289,
203,
203,
1377,
2254,
5034,
1384,
21,
273,
261,
1615,
397,
404,
13,
380,
1241,
67,
3890,
31,
203,
1377,
2254,
5034,
1384,
22,
273,
261,
1615,
397,
576,
13,
380,
1241,
67,
3890,
31,
203,
203,
1377,
509,
5034,
272,
558,
273,
353,
67,
31755,
67,
21733,
6890,
692,
509,
5034,
12,
11890,
5034,
12,
92,
21,
3719,
397,
509,
5034,
12,
2
] |
./partial_match/1/0x2CA461E4597101cAb27ed4ac9e3f1ceAA480f6de/sources/MultipleArbitrableTransactionWithFee.sol | * @dev Calculate the amount to be paid in wei according to feeRecipientBasisPoint for a particular amount. @param _amount Amount to pay in wei./ | function calculateFeeRecipientAmount(uint _amount) internal view returns(uint feeAmount){
feeAmount = (_amount * feeRecipientBasisPoint) / 10000;
}
| 2,841,750 | [
1,
8695,
326,
3844,
358,
506,
30591,
316,
732,
77,
4888,
358,
14036,
18241,
11494,
291,
2148,
364,
279,
6826,
3844,
18,
282,
389,
8949,
16811,
358,
8843,
316,
732,
77,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
14667,
18241,
6275,
12,
11890,
389,
8949,
13,
2713,
1476,
1135,
12,
11890,
14036,
6275,
15329,
203,
3639,
14036,
6275,
273,
261,
67,
8949,
380,
14036,
18241,
11494,
291,
2148,
13,
342,
12619,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
/*
This contract is an extension of the fileSale contract based on FairSwap(https://github.com/lEthDev/FairSwap).
In contains only the methods required for the optimistic mode and a function that calls a 'fileSalePessimistic' contract for dispute resolution.
*/
// abstract 'fileSalePessimistic' contract
contract fileSalePessimistic {
function startDisputeResolution(address _sender, bytes32 _key, uint[] _Q) public;
function () payable public;
}
contract fileSaleOptimistic {
uint constant price = XXXPRICEXXX; // price given in wei
address public receiver = XXXADDRESSRECEIVERXXX;
address public sender;
bytes32 public keyCommit = XXXKEYCOMMITMENTXXX;
bytes32 public key;
address public verifierContactAddress = XXXVERIFIERCONTRACTADDRESSXXX;
enum stage {start, active, initialized, revealed, challenged}
stage public phase = stage.start;
uint public timeout;
uint public challengeLimit = XXXCHALLENGELIMITXXX;
uint constant feeReceiver = XXXRECEIVERFEEXXX; // receiver fee given in wei
// function modifier to only allow calling the function in the right phase only from the correct party
modifier allowed(address p, stage s) {
require(phase == s);
require(msg.sender == p);
_;
}
// go to next phase
function nextStage(stage s) internal {
phase = s;
timeout = now + 10 minutes;
}
/*
* Initialization phase
*/
// constructor is initialize function
constructor () public {
sender = msg.sender;
nextStage(stage.active);
}
// function accept
function accept() allowed(receiver, stage.active) payable public {
require (msg.value >= price);
nextStage(stage.initialized);
}
/*
* Abort during the Initialization phase
*/
// function abort can be accessed by sender and receiver
function abort() public {
if (phase == stage.active) selfdestruct(sender);
if (phase == stage.initialized) selfdestruct(receiver);
}
/*
* Revealing phase
*/
function revealKey (bytes32 _key) allowed(sender, stage.initialized) public {
require(keyCommit == keccak256(_key));
key = _key;
nextStage(stage.revealed);
}
/*
* Finalization phase
*/
// function refund implements the 'challenge timeout', 'response timeout', and 'finalize' (executable by the sender) functionalities
function refund() public {
require(now > timeout);
if (phase == stage.revealed) selfdestruct(sender);
if (phase == stage.challenged) selfdestruct(receiver);
}
// function noComplain implements the 'finalize' functionality executed by the receiver
function noComplain() allowed(receiver, stage.revealed) public {
selfdestruct(sender);
}
function challenge(uint[] _Q) payable public {
require(msg.sender == receiver);
require(phase == stage.revealed);
require(_Q.length <= challengeLimit);
require(msg.value >= _Q.length * feeReceiver);
nextStage(stage.challenged);
fileSalePessimistic verifier = fileSalePessimistic(verifierContactAddress);
address(verifier).transfer(address(this).balance);
verifier.startDisputeResolution(sender, key, _Q);
}
}
| Initialization phase/ constructor is initialize function | constructor () public {
sender = msg.sender;
nextStage(stage.active);
}
| 894,425 | [
1,
17701,
6855,
19,
3885,
353,
4046,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1832,
1071,
288,
203,
3639,
5793,
273,
1234,
18,
15330,
31,
203,
3639,
1024,
8755,
12,
12869,
18,
3535,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-12
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.11;
/// @title ERC165 Interface
/// @dev https://eips.ethereum.org/EIPS/eip-165
/// @author Andreas Bigger <[emailΒ protected]>
interface IERC165 {
/// @dev Returns if the contract implements the defined interface
/// @param interfaceId the 4 byte interface signature
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/// @title ERC721 Interface
/// @dev https://eips.ethereum.org/EIPS/eip-721
/// @author Andreas Bigger <[emailΒ protected]>
interface IERC721 is IERC165 {
/// @dev Emitted when a token is transferred
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/// @dev Emitted when a token owner approves `approved`
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/// @dev Emitted when `owner` enables or disables `operator` for all tokens
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/// @dev Returns the number of tokens owned by `owner`
function balanceOf(address owner) external view returns (uint256 balance);
/// @dev Returns the owner of token with id `tokenId`
function ownerOf(uint256 tokenId) external view returns (address owner);
/// @dev Safely transfers the token with id `tokenId`
/// @dev Requires the sender to be approved through an `approve` or `setApprovalForAll`
/// @dev Emits a Transfer Event
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/// @dev Transfers the token with id `tokenId`
/// @dev Requires the sender to be approved through an `approve` or `setApprovalForAll`
/// @dev Emits a Transfer Event
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/// @dev Approves `to` to transfer the given token
/// @dev Approval is reset on transfer
/// @dev Caller must be the owner or approved
/// @dev Only one address can be approved at a time
/// @dev Emits an Approval Event
function approve(address to, uint256 tokenId) external;
/// @dev Returns the address approved for the given token
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/// @dev Sets an operator as approved or disallowed for all tokens owned by the caller
/// @dev Emits an ApprovalForAll Event
function setApprovalForAll(address operator, bool _approved) external;
/// @dev Returns if the operator is allowed approved for owner's tokens
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/// @dev Safely transfers a token with id `tokenId`
/// @dev Emits a Transfer Event
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/// Fee Overflow
/// @param sender address that caused the revert
/// @param fee uint256 proposed fee percent
error FeeOverflow(address sender, uint256 fee);
/// Non Coordinator
/// @param sender The coordinator impersonator address
/// @param coordinator The expected coordinator address
error NonCoordinator(address sender, address coordinator);
/// @title Coordinator
/// @notice Coordinates fees and receivers
/// @author Andreas Bigger <[emailΒ protected]>
contract Coordinator {
/// @dev This contracts coordinator
address public coordinator;
/// @dev Address of the profit receiver
address payable public profitReceiver;
/// @dev Pack the below variables using uint32 values
/// @dev Fee paid by bots
uint32 public botFeeBips;
/// @dev The absolute maximum fee in bips (10,000 bips or 100%)
uint32 public constant MAXIMUM_FEE = 10_000;
/// @dev Modifier restricting msg.sender to solely be the coordinatoooor
modifier onlyCoordinator() {
if (msg.sender != coordinator) revert NonCoordinator(msg.sender, coordinator);
_;
}
/// @notice Constructor sets coordinator, profit receiver, and fee in bips
/// @param _profitReceiver the address of the profit receiver
/// @param _botFeeBips the fee in bips
/// @dev The fee cannot be greater than 100%
constructor(address _profitReceiver, uint32 _botFeeBips) {
if (botFeeBips > MAXIMUM_FEE) revert FeeOverflow(msg.sender, _botFeeBips);
coordinator = msg.sender;
profitReceiver = payable(_profitReceiver);
botFeeBips = _botFeeBips;
}
/// @notice Coordinator can change the stored Coordinator address
/// @param newCoordinator The address of the new coordinator
function changeCoordinator(address newCoordinator) external onlyCoordinator {
coordinator = newCoordinator;
}
/// @notice The Coordinator can change the address that receives the fee profits
/// @param newProfitReceiver The address of the new profit receiver
function changeProfitReceiver(address newProfitReceiver) external onlyCoordinator {
profitReceiver = payable(newProfitReceiver);
}
/// @notice The Coordinator can change the fee amount in bips
/// @param newBotFeeBips The unsigned integer representing the new fee amount in bips
/// @dev The fee cannot be greater than 100%
function changeBotFeeBips(uint32 newBotFeeBips) external onlyCoordinator {
if (newBotFeeBips > MAXIMUM_FEE) revert FeeOverflow(msg.sender, newBotFeeBips);
botFeeBips = newBotFeeBips;
}
}
/// Require EOA
error NonEOA();
/// Order Out of Bounds
/// @param sender The address of the msg sender
/// @param orderNumber The requested order number for the user (maps to an order id)
/// @param maxOrderCount The maximum number of orders a user has placed
error OrderOOB(address sender, uint256 orderNumber, uint256 maxOrderCount);
/// Order Nonexistent
/// @param user The address of the user who owns the order
/// @param orderNumber The requested order number for the user (maps to an order id)
/// @param orderId The order's Id
error OrderNonexistent(address user, uint256 orderNumber, uint256 orderId);
/// Invalid Amount
/// @param sender The address of the msg sender
/// @param priceInWeiEach The order's priceInWeiEach
/// @param quantity The order's quantity
/// @param tokenAddress The order's token address
error InvalidAmount(address sender, uint256 priceInWeiEach, uint256 quantity, address tokenAddress);
/// Insufficient price in wei
/// @param sender The address of the msg sender
/// @param orderId The order's Id
/// @param tokenId The ERC721 Token ID
/// @param expectedPriceInWeiEach The expected priceInWeiEach
/// @param priceInWeiEach The order's actual priceInWeiEach from internal store
error InsufficientPrice(address sender, uint256 orderId, uint256 tokenId, uint256 expectedPriceInWeiEach, uint256 priceInWeiEach);
/// Inconsistent Arguments
/// @param sender The address of the msg sender
error InconsistentArguments(address sender);
/// @title YobotERC721LimitOrder
/// @author Andreas Bigger <[emailΒ protected]>
/// @notice Original contract implementation was open-sourced and verified on etherscan at:
/// https://etherscan.io/address/0x56E6FA0e461f92644c6aB8446EA1613F4D72a756#code
/// with the original UI at See ArtBotter.io
/// @notice Permissionless Broker for Generalized ERC721 Minting using Flashbot Searchers
contract YobotERC721LimitOrder is Coordinator {
/// @notice A user's order
struct Order {
/// @dev The Order owner
address owner;
/// @dev The Order's Token Address
address tokenAddress;
/// @dev the price to pay for each erc721 token
uint256 priceInWeiEach;
/// @dev the quantity of tokens to pay
uint256 quantity;
/// @dev the order number for the user, used for reverse mapping
uint256 num;
}
/// @dev Current Order Id
/// @dev Starts at 1, 0 is a deleted order
uint256 public orderId = 1;
/// @dev Mapping from order id to an Order
mapping(uint256 => Order) public orderStore;
/// @dev user => order number => order id
mapping(address => mapping(uint256 => uint256)) public userOrders;
/// @dev The number of user orders
mapping(address => uint256) public userOrderCount;
/// @dev bot => eth balance
mapping(address => uint256) public balances;
/// @notice Emitted whenever a respective individual executes a function
/// @param _user the address of the sender executing the action - used primarily for indexing
/// @param _tokenAddress The token address to interact with
/// @param _priceInWeiEach The bid price in wei for each ERC721 Token
/// @param _quantity The number of tokens
/// @param _action The action being emitted
/// @param _orderId The order's id
/// @param _orderNum The user<>num order
/// @param _tokenId The optional token id (used primarily on bot fills)
event Action(
address indexed _user,
address indexed _tokenAddress,
uint256 indexed _priceInWeiEach,
uint256 _quantity,
string _action,
uint256 _orderId,
uint256 _orderNum,
uint256 _tokenId
);
/// @notice Creates a new yobot erc721 limit order broker
/// @param _profitReceiver The profit receiver for fees
/// @param _botFeeBips The fee rake
// solhint-disable-next-line no-empty-blocks
constructor(address _profitReceiver, uint32 _botFeeBips) Coordinator(_profitReceiver, _botFeeBips) {}
////////////////////////////////////////////////////
/// ORDERS ///
////////////////////////////////////////////////////
/// @notice places an open order for a user
/// @notice users should place orders ONLY for token addresses that they trust
/// @param _tokenAddress the erc721 token address
/// @param _quantity the number of tokens
function placeOrder(address _tokenAddress, uint256 _quantity) external payable {
// Removes user foot-guns and garuantees user can receive NFTs
// We disable linting against tx-origin to purposefully allow EOA checks
// solhint-disable-next-line avoid-tx-origin
if (msg.sender != tx.origin) revert NonEOA();
// Check to make sure the bids are gt zero
uint256 priceInWeiEach = msg.value / _quantity;
if (priceInWeiEach == 0 || _quantity == 0) revert InvalidAmount(msg.sender, priceInWeiEach, _quantity, _tokenAddress);
// Update the Order Id
uint256 currOrderId = orderId;
orderId += 1;
// Get the current order number for the user
uint256 currUserOrderCount = userOrderCount[msg.sender];
// Create a new Order
orderStore[currOrderId].owner = msg.sender;
orderStore[currOrderId].tokenAddress = _tokenAddress;
orderStore[currOrderId].priceInWeiEach = priceInWeiEach;
orderStore[currOrderId].quantity = _quantity;
orderStore[currOrderId].num = currUserOrderCount;
// Update the user's orders
userOrders[msg.sender][currUserOrderCount] = currOrderId;
userOrderCount[msg.sender] += 1;
emit Action(msg.sender, _tokenAddress, priceInWeiEach, _quantity, "ORDER_PLACED", currOrderId, currUserOrderCount, 0);
}
/// @notice Cancels a user's order for the given erc721 token
/// @param _orderNum The user's order number
function cancelOrder(uint256 _orderNum) external {
// Check to make sure the user's order is in bounds
uint256 currUserOrderCount = userOrderCount[msg.sender];
if (_orderNum >= currUserOrderCount) revert OrderOOB(msg.sender, _orderNum, currUserOrderCount);
// Get the id for the given user order num
uint256 currOrderId = userOrders[msg.sender][_orderNum];
// Revert if the order id is 0, already deleted or filled
if (currOrderId == 0) revert OrderNonexistent(msg.sender, _orderNum, currOrderId);
// Get the order
Order memory order = orderStore[currOrderId];
uint256 amountToSendBack = order.priceInWeiEach * order.quantity;
if (amountToSendBack == 0) revert InvalidAmount(msg.sender, order.priceInWeiEach, order.quantity, order.tokenAddress);
// Delete the order
delete orderStore[currOrderId];
// Delete the order id from the userOrders mapping
delete userOrders[msg.sender][_orderNum];
// Send the value back to the user
sendValue(payable(msg.sender), amountToSendBack);
emit Action(msg.sender, order.tokenAddress, order.priceInWeiEach, order.quantity, "ORDER_CANCELLED", currOrderId, _orderNum, 0);
}
////////////////////////////////////////////////////
/// BOT LOGIC ///
////////////////////////////////////////////////////
/// @notice Fill a single order
/// @param _orderId The id of the order
/// @param _tokenId the token id to mint
/// @param _expectedPriceInWeiEach the price to pay
/// @param _profitTo the address to send the fee to
/// @param _sendNow whether or not to send the fee now
function fillOrder(
uint256 _orderId,
uint256 _tokenId,
uint256 _expectedPriceInWeiEach,
address _profitTo,
bool _sendNow
) public returns (uint256) {
Order storage order = orderStore[_orderId];
// Make sure the order isn't deleted
uint256 orderIdFromMap = userOrders[order.owner][order.num];
if (order.quantity == 0 || order.priceInWeiEach == 0 || orderIdFromMap == 0) revert InvalidAmount(order.owner, order.priceInWeiEach, order.quantity, order.tokenAddress);
// Protects bots from users frontrunning them
if (order.priceInWeiEach < _expectedPriceInWeiEach) revert InsufficientPrice(msg.sender, _orderId, _tokenId, _expectedPriceInWeiEach, order.priceInWeiEach);
// Transfer NFT to user (benign reentrancy possible here)
// ERC721-compliant contracts revert on failure here
IERC721(order.tokenAddress).safeTransferFrom(msg.sender, order.owner, _tokenId);
// This reverts on underflow
order.quantity -= 1;
uint256 botFee = (order.priceInWeiEach * botFeeBips) / 10_000;
balances[profitReceiver] += botFee;
// Pay the bot with the remaining amount
uint256 botPayment = order.priceInWeiEach - botFee;
if (_sendNow) {
sendValue(payable(_profitTo), botPayment);
} else {
balances[_profitTo] += botPayment;
}
// Emit the action later so we can log trace on a bot dashboard
emit Action(order.owner, order.tokenAddress, order.priceInWeiEach, order.quantity, "ORDER_FILLED", _orderId, order.num, _tokenId);
// Clear up if the quantity is now 0
if (order.quantity == 0) {
delete orderStore[_orderId];
userOrders[order.owner][order.num] = 0;
}
// RETURN
return botPayment;
}
/// @notice allows a bot to fill multiple outstanding orders
/// @dev there should be one token id and token price specified for each users
/// @dev So, _users.length == _tokenIds.length == _expectedPriceInWeiEach.length
/// @param _orderIds a list of order ids
/// @param _tokenIds a list of token ids
/// @param _expectedPriceInWeiEach the price of each token
/// @param _profitTo the address to send the bot's profit to
/// @param _sendNow whether the profit should be sent immediately
function fillMultipleOrdersOptimized(
uint256[] memory _orderIds,
uint256[] memory _tokenIds,
uint256[] memory _expectedPriceInWeiEach,
address _profitTo,
bool _sendNow
) external returns (uint256[] memory) {
if (_orderIds.length != _tokenIds.length || _tokenIds.length != _expectedPriceInWeiEach.length) revert InconsistentArguments(msg.sender);
uint256[] memory output = new uint256[](_orderIds.length);
for (uint256 i = 0; i < _orderIds.length; i++) {
output[i] = fillOrder(_orderIds[i], _tokenIds[i], _expectedPriceInWeiEach[i], _profitTo, _sendNow);
}
return output;
}
/// @notice allows a bot to fill multiple outstanding orders with
/// @dev all argument array lengths should be equal
/// @param _orderIds a list of order ids
/// @param _tokenIds a list of token ids
/// @param _expectedPriceInWeiEach the price of each token
/// @param _profitTo the addresses to send the bot's profit to
/// @param _sendNow whether the profit should be sent immediately
function fillMultipleOrdersUnOptimized(
uint256[] memory _orderIds,
uint256[] memory _tokenIds,
uint256[] memory _expectedPriceInWeiEach,
address[] memory _profitTo,
bool[] memory _sendNow
) external returns (uint256[] memory) {
if (
_orderIds.length != _tokenIds.length
|| _tokenIds.length != _expectedPriceInWeiEach.length
|| _expectedPriceInWeiEach.length != _profitTo.length
|| _profitTo.length != _sendNow.length
) revert InconsistentArguments(msg.sender);
// Fill the orders iteratively
uint256[] memory output = new uint256[](_orderIds.length);
for (uint256 i = 0; i < _orderIds.length; i++) {
output[i] = fillOrder(_orderIds[i], _tokenIds[i], _expectedPriceInWeiEach[i], _profitTo[i], _sendNow[i]);
}
return output;
}
////////////////////////////////////////////////////
/// WITHDRAWALS ///
////////////////////////////////////////////////////
/// @notice Allows profitReceiver and bots to withdraw their fees
/// @dev delete balances on withdrawal to free up storage
function withdraw() external {
// EFFECTS
uint256 amount = balances[msg.sender];
delete balances[msg.sender];
// INTERACTIONS
sendValue(payable(msg.sender), amount);
}
////////////////////////////////////////////////////
/// HELPERS ///
////////////////////////////////////////////////////
/// @notice sends ETH out of this contract to the recipient
/// @dev OpenZeppelin's sendValue function
/// @param recipient the recipient to send the ETH to | payable
/// @param amount the amount of ETH to send
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");
}
/// @notice Returns an open order for a user and order number pair
/// @param _user The user
/// @param _orderNum The order number (NOT ID)
function viewUserOrder(address _user, uint256 _orderNum) public view returns (Order memory) {
// Revert if the order id is 0
uint256 _orderId = userOrders[_user][_orderNum];
if (_orderId == 0) revert OrderNonexistent(_user, _orderNum, _orderId);
return orderStore[_orderId];
}
/// @notice Returns all open orders for a given user
/// @param _user The user
function viewUserOrders(address _user) public view returns (Order[] memory output) {
uint256 _userOrderCount = userOrderCount[_user];
output = new Order[](_userOrderCount);
for (uint256 i = 0; i < _userOrderCount; i += 1) {
uint256 _orderId = userOrders[_user][i];
output[i] = orderStore[_orderId];
}
}
/// @notice Returns the open orders for a list of users
/// @param _users the users address
function viewMultipleOrders(address[] memory _users) public view returns (Order[][] memory output) {
Order[][] memory output = new Order[][](_users.length);
for (uint256 i = 0; i < _users.length; i++) {
output[i] = viewUserOrders(_users[i]);
}
}
} | @dev The number of user orders | mapping(address => uint256) public userOrderCount;
| 6,549,960 | [
1,
1986,
1300,
434,
729,
11077,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
729,
2448,
1380,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// File: contracts-origin/AetherAccessControl.sol
/// @title A facet of AetherCore that manages special access privileges.
/// @dev See the AetherCore contract documentation to understand how the various contract facets are arranged.
contract AetherAccessControl {
// This facet controls access control for Laputa. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the AetherCore constructor.
//
// - The CFO: The CFO can withdraw funds from AetherCore and its auction contracts.
//
// - The COO: The COO can release properties to auction.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(this.balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
// File: contracts-origin/AetherBase.sol
/// @title Base contract for Aether. Holds all common structs, events and base variables.
/// @author Project Aether (https://www.aether.city)
/// @dev See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherBase is AetherAccessControl {
/*** EVENTS ***/
/// @dev The Construct event is fired whenever a property updates.
event Construct (
address indexed owner,
uint256 propertyId,
PropertyClass class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
string data
);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every
/// time a property ownership is assigned.
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/*** DATA ***/
enum PropertyClass { DISTRICT, BUILDING, UNIT }
/// @dev The main Property struct. Every property in Aether is represented
/// by a variant of this structure.
struct Property {
uint32 parent;
PropertyClass class;
uint8 x;
uint8 y;
uint8 z;
uint8 dx;
uint8 dz;
}
/*** STORAGE ***/
/// @dev Ensures that property occupies unique part of the universe.
bool[100][100][100] public world;
/// @dev An array containing the Property struct for all properties in existence. The ID
/// of each property is actually an index into this array.
Property[] properties;
/// @dev An array containing the district addresses in existence.
uint256[] districts;
/// @dev A measure of world progression.
uint256 public progress;
/// @dev The fee associated with constructing a unit property.
uint256 public unitCreationFee = 0.05 ether;
/// @dev Keeps track whether updating data is paused.
bool public updateEnabled = true;
/// @dev A mapping from property IDs to the address that owns them. All properties have
/// some valid owner address, even gen0 properties are created with a non-zero owner.
mapping (uint256 => address) public propertyIndexToOwner;
/// @dev A mapping from property IDs to the data that is stored on them.
mapping (uint256 => string) public propertyIndexToData;
/// @dev A mapping from owner address to count of tokens that address owns.
/// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev Mappings between property nodes.
mapping (uint256 => uint256) public districtToBuildingsCount;
mapping (uint256 => uint256[]) public districtToBuildings;
mapping (uint256 => uint256) public buildingToUnitCount;
mapping (uint256 => uint256[]) public buildingToUnits;
/// @dev A mapping from building propertyId to unit construction privacy.
mapping (uint256 => bool) public buildingIsPublic;
/// @dev A mapping from PropertyIDs to an address that has been approved to call
/// transferFrom(). Each Property can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public propertyIndexToApproved;
/// @dev Assigns ownership of a specific Property to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// since the number of properties is capped to 2^32
// there is no way to overflow this
ownershipTokenCount[_to]++;
// transfer ownership
propertyIndexToOwner[_tokenId] = _to;
// When creating new properties _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete propertyIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function _createUnit(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(!world[_x][_y][_z]);
world[_x][_y][_z] = true;
return _createProperty(
_parent,
PropertyClass.UNIT,
_x,
_y,
_z,
0,
0,
_owner
);
}
function _createBuilding(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner,
bool _public
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
// Looping over world space.
for(uint256 i = 0; i < _dx; i++) {
for(uint256 j = 0; j <_dz; j++) {
if (world[_x + i][0][_z + j]) {
revert();
}
world[_x + i][0][_z + j] = true;
}
}
uint propertyId = _createProperty(
_parent,
PropertyClass.BUILDING,
_x,
_y,
_z,
_dx,
_dz,
_owner
);
districtToBuildingsCount[_parent]++;
districtToBuildings[_parent].push(propertyId);
buildingIsPublic[propertyId] = _public;
return propertyId;
}
function _createDistrict(
uint256 _x,
uint256 _z,
uint256 _dx,
uint256 _dz
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
uint propertyId = _createProperty(
districts.length,
PropertyClass.DISTRICT,
_x,
0,
_z,
_dx,
_dz,
cooAddress
);
districts.push(propertyId);
return propertyId;
}
/// @dev An internal method that creates a new property and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Construct event
/// and a Transfer event.
function _createProperty(
uint256 _parent,
PropertyClass _class,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
require(_parent == uint256(uint32(_parent)));
require(uint256(_class) <= 3);
Property memory _property = Property({
parent: uint32(_parent),
class: _class,
x: uint8(_x),
y: uint8(_y),
z: uint8(_z),
dx: uint8(_dx),
dz: uint8(_dz)
});
uint256 _tokenId = properties.push(_property) - 1;
// It's never going to happen, 4 billion properties is A LOT, but
// let's just be 100% sure we never let this happen.
require(_tokenId <= 4294967295);
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
""
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, _tokenId);
return _tokenId;
}
/// @dev Computing height of a building with respect to city progression.
function _computeHeight(
uint256 _x,
uint256 _z,
uint256 _height
) internal view returns (uint256) {
uint256 x = _x < 50 ? 50 - _x : _x - 50;
uint256 z = _z < 50 ? 50 - _z : _z - 50;
uint256 distance = x > z ? x : z;
if (distance > progress) {
return 1;
}
uint256 scale = 100 - (distance * 100) / progress ;
uint256 height = 2 * progress * _height * scale / 10000;
return height > 0 ? height : 1;
}
/// @dev Convenience function to see if this building has room for a unit.
function canCreateUnit(uint256 _buildingId)
public
view
returns(bool)
{
Property storage _property = properties[_buildingId];
if (_property.class == PropertyClass.BUILDING &&
(buildingIsPublic[_buildingId] ||
propertyIndexToOwner[_buildingId] == msg.sender)
) {
uint256 totalVolume = _property.dx * _property.dz *
(_computeHeight(_property.x, _property.z, _property.y) - 1);
uint256 totalUnits = buildingToUnitCount[_buildingId];
return totalUnits < totalVolume;
}
return false;
}
/// @dev This internal function skips all validation checks. Ensure that
// canCreateUnit() is required before calling this method.
function _createUnitHelper(uint256 _buildingId, address _owner)
internal
returns(uint256)
{
// Grab a reference to the property in storage.
Property storage _property = properties[_buildingId];
uint256 totalArea = _property.dx * _property.dz;
uint256 index = buildingToUnitCount[_buildingId];
// Calculate next location.
uint256 y = index / totalArea + 1;
uint256 intermediate = index % totalArea;
uint256 z = intermediate / _property.dx;
uint256 x = intermediate % _property.dx;
uint256 unitId = _createUnit(
_buildingId,
x + _property.x,
y,
z + _property.z,
_owner
);
buildingToUnitCount[_buildingId]++;
buildingToUnits[_buildingId].push(unitId);
// Return the new unit's ID.
return unitId;
}
/// @dev Update allows for setting a building privacy.
function updateBuildingPrivacy(uint _tokenId, bool _public) public {
require(propertyIndexToOwner[_tokenId] == msg.sender);
buildingIsPublic[_tokenId] = _public;
}
/// @dev Update allows for setting the data associated to a property.
function updatePropertyData(uint _tokenId, string _data) public {
require(updateEnabled);
address _owner = propertyIndexToOwner[_tokenId];
require(msg.sender == _owner);
propertyIndexToData[_tokenId] = _data;
Property memory _property = properties[_tokenId];
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
_data
);
}
}
// File: contracts-origin/ERC721Draft.sol
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
// File: contracts-origin/AetherOwnership.sol
/// @title The facet of the Aether core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherOwnership is AetherBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name = "Aether";
string public symbol = "AETH";
function implementsERC721() public pure returns (bool)
{
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Property.
/// @param _claimant the address we are validating against.
/// @param _tokenId property id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Property.
/// @param _claimant the address we are confirming property is approved for.
/// @param _tokenId property id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Properties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
propertyIndexToApproved[_tokenId] = _approved;
}
/// @dev Transfers a property owned by this contract to the specified address.
/// Used to rescue lost properties. (There is no "proper" flow where this contract
/// should be the owner of any Property. This function exists for us to reassign
/// the ownership of Properties that users may have accidentally sent to our address.)
/// @param _propertyId - ID of property
/// @param _recipient - Address to send the property to
function rescueLostProperty(uint256 _propertyId, address _recipient) public onlyCOO whenNotPaused {
require(_owns(this, _propertyId));
_transfer(this, _recipient, _propertyId);
}
/// @notice Returns the number of Properties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Property to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Laputa specifically) or your Property may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Property to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// You can only send your own property.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Property via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Property that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Property owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Property to be transfered.
/// @param _to The address that should take ownership of the Property. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Property to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Properties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return properties.length;
}
function totalDistrictSupply() public view returns(uint count) {
return districts.length;
}
/// @notice Returns the address currently assigned ownership of a given Property.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = propertyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Property IDs assigned to an address.
/// @param _owner The owner whose Properties we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Kitty array looking for cats belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalProperties = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all properties have IDs starting at 1 and increasing
// sequentially up to the totalProperties count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalProperties; tokenId++) {
if (propertyIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
}
// File: contracts-origin/Auction/ClockAuctionBase.sol
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev DON'T give me your money.
function() external {}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(_value <= 18446744073709551615);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(_value < 340282366920938463463374607431768211455);
_;
}
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the incoming bid is higher than the current
// price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
// File: contracts-origin/Auction/ClockAuction.sol
/// @title Clock auction for non-fungible tokens.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.implementsERC721());
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
public
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
public
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
// File: contracts-origin/Auction/AetherClockAuction.sol
/// @title Clock auction modified for sale of property
contract AetherClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isAetherClockAuction = true;
// Tracks last 5 sale price of gen0 property sales
uint256 public saleCount;
uint256[5] public lastSalePrices;
// Delegate constructor
function AetherClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
public
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastSalePrices[saleCount % 5] = price;
saleCount++;
}
}
function averageSalePrice() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastSalePrices[i];
}
return sum / 5;
}
}
// File: contracts-origin/AetherAuction.sol
/// @title Handles creating auctions for sale and siring of properties.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract AetherAuction is AetherOwnership{
/// @dev The address of the ClockAuction contract that handles sales of Aether. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
AetherClockAuction public saleAuction;
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) public onlyCEO {
AetherClockAuction candidateContract = AetherClockAuction(_address);
// NOTE: verify that a contract is what we expect
require(candidateContract.isAetherClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a property up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _propertyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If property is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _propertyId));
_approve(_propertyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the property.
saleAuction.createAuction(
_propertyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the AetherCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCOO {
saleAuction.withdrawBalance();
}
}
// File: contracts-origin/AetherConstruct.sol
// Auction wrapper functions
/// @title all functions related to creating property
contract AetherConstruct is AetherAuction {
uint256 public districtLimit = 16;
uint256 public startingPrice = 1 ether;
uint256 public auctionDuration = 1 days;
/// @dev Units can be contructed within public and owned buildings.
function createUnit(uint256 _buildingId)
public
payable
returns(uint256)
{
require(canCreateUnit(_buildingId));
require(msg.value >= unitCreationFee);
if (msg.value > unitCreationFee)
msg.sender.transfer(msg.value - unitCreationFee);
uint256 propertyId = _createUnitHelper(_buildingId, msg.sender);
return propertyId;
}
/// @dev Creation of unit properties. Only callable by COO
function createUnitOmni(
uint32 _buildingId,
address _owner
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
require(canCreateUnit(_buildingId));
_createUnitHelper(_buildingId, _owner);
}
/// @dev Creation of building properties. Only callable by COO
function createBuildingOmni(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
address _owner,
bool _open
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
_createBuilding(_districtId, _x, _y, _z, _dx, _dz, _owner, _open);
}
/// @dev Creation of district properties, up to a limit. Only callable by COO
function createDistrictOmni(
uint8 _x,
uint8 _z,
uint8 _dx,
uint8 _dz
)
public
onlyCOO
{
require(districts.length < districtLimit);
_createDistrict(_x, _z, _dx, _dz);
}
/// @dev Creates a new property with the given details and
/// creates an auction for it. Only callable by COO.
function createBuildingAuction(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
bool _open
) public onlyCOO {
uint256 propertyId = _createBuilding(_districtId, _x, _y, _z, _dx, _dz, address(this), _open);
_approve(propertyId, saleAuction);
saleAuction.createAuction(
propertyId,
_computeNextPrice(),
0,
auctionDuration,
address(this)
);
}
/// @dev Updates the minimum payment required for calling createUnit(). Can only
/// be called by the COO address.
function setUnitCreationFee(uint256 _value) public onlyCOO {
unitCreationFee = _value;
}
/// @dev Update world progression factor allowing for buildings to grow taller
// as the city expands. Only callable by COO.
function setProgress(uint256 _progress) public onlyCOO {
require(_progress <= 100);
require(_progress > progress);
progress = _progress;
}
/// @dev Set property data updates flag. Only callable by COO.
function setUpdateState(bool _updateEnabled) public onlyCOO {
updateEnabled = _updateEnabled;
}
/// @dev Computes the next auction starting price, given the average of the past
/// 5 prices + 50%.
function _computeNextPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageSalePrice();
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
require(avePrice < 340282366920938463463374607431768211455);
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < startingPrice) {
nextPrice = startingPrice;
}
return nextPrice;
}
}
// File: contracts-origin/AetherCore.sol
/// @title Aether: A city on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
contract AetherCore is AetherConstruct {
// This is the main Aether contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. The auctions are seperate since their logic is somewhat complex
// and there's always a risk of subtle bugs. By keeping them in their own contracts, we can upgrade
// them without disrupting the main contract that tracks property ownership.
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of Aether. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - AetherBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - AetherAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - AetherOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - AetherAuction: Here we have the public methods for auctioning or bidding on property.
// The actual auction functionality is handled in two sibling contracts while auction
// creation and bidding is mostly mediated through this facet of the core contract.
//
// - AetherConstruct: This final facet contains the functionality we use for creating new gen0 cats.
// the community is new).
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main Aether smart contract instance.
function AetherCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) public onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @notice Returns all the relevant information about a specific property.
/// @param _id The ID of the property of interest.
function getProperty(uint256 _id)
public
view
returns (
uint32 parent,
uint8 class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
uint8 height
) {
Property storage property = properties[_id];
parent = uint32(property.parent);
class = uint8(property.class);
height = uint8(property.y);
if (property.class == PropertyClass.BUILDING) {
y = uint8(_computeHeight(property.x, property.z, property.y));
} else {
y = uint8(property.y);
}
x = uint8(property.x);
z = uint8(property.z);
dx = uint8(property.dx);
dz = uint8(property.dz);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
} | @dev Updates the minimum payment required for calling createUnit(). Can only be called by the COO address. | function setUnitCreationFee(uint256 _value) public onlyCOO {
unitCreationFee = _value;
}
| 1,090,919 | [
1,
5121,
326,
5224,
5184,
1931,
364,
4440,
752,
2802,
7675,
4480,
1338,
225,
506,
2566,
635,
326,
7910,
51,
1758,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
2802,
9906,
14667,
12,
11890,
5034,
389,
1132,
13,
1071,
1338,
3865,
51,
288,
203,
3639,
2836,
9906,
14667,
273,
389,
1132,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
import "@c-layer/common/contracts/operable/Operable.sol";
import "@c-layer/common/contracts/lifecycle/Pausable.sol";
import "../interface/ITokensale.sol";
/**
* @title BaseTokensale
* @dev Base Tokensale contract
*
* @author Cyril Lapinte - <[email protected]>
* SPDX-License-Identifier: MIT
*
* Error messages
* TOS01: token price must be strictly positive
* TOS02: price unit must be strictly positive
* TOS03: Token transfer must be successfull
* TOS04: No ETH to refund
* TOS05: Cannot invest 0 tokens
* TOS06: Cannot invest if there are no tokens to buy
* TOS07: Only exact amount is authorized
*/
contract BaseTokensale is ITokensale, Operable, Pausable {
/* General sale details */
IERC20 internal token_;
address payable internal vaultETH_;
address internal vaultERC20_;
uint256 internal tokenPrice_;
uint256 internal priceUnit_;
uint256 internal totalRaised_;
uint256 internal totalTokensSold_;
uint256 internal totalUnspentETH_;
uint256 internal totalRefundedETH_;
struct Investor {
uint256 unspentETH;
uint256 invested;
uint256 tokens;
}
mapping(address => Investor) internal investors;
/**
* @dev constructor
*/
constructor(
IERC20 _token,
address _vaultERC20,
address payable _vaultETH,
uint256 _tokenPrice,
uint256 _priceUnit
) {
require(_tokenPrice > 0, "TOS01");
require(_priceUnit > 0, "TOS02");
token_ = _token;
vaultERC20_ = _vaultERC20;
vaultETH_ = _vaultETH;
tokenPrice_ = _tokenPrice;
priceUnit_ = _priceUnit;
}
/**
* @dev fallback function
*/
//solhint-disable-next-line no-complex-fallback
receive() external override payable {
investETH();
}
/* Investment */
function investETH() public virtual override payable
{
Investor storage investor = investorInternal(msg.sender);
uint256 amountETH = investor.unspentETH + msg.value;
investInternal(msg.sender, amountETH, false);
}
/**
* @dev returns the token sold
*/
function token() public override view returns (IERC20) {
return token_;
}
/**
* @dev returns the vault use to
*/
function vaultETH() public override view returns (address) {
return vaultETH_;
}
/**
* @dev returns the vault to receive ETH
*/
function vaultERC20() public override view returns (address) {
return vaultERC20_;
}
/**
* @dev returns token price
*/
function tokenPrice() public override view returns (uint256) {
return tokenPrice_;
}
/**
* @dev returns price unit
*/
function priceUnit() public override view returns (uint256) {
return priceUnit_;
}
/**
* @dev returns total raised
*/
function totalRaised() public override view returns (uint256) {
return totalRaised_;
}
/**
* @dev returns total tokens sold
*/
function totalTokensSold() public override view returns (uint256) {
return totalTokensSold_;
}
/**
* @dev returns total unspent ETH
*/
function totalUnspentETH() public override view returns (uint256) {
return totalUnspentETH_;
}
/**
* @dev returns total refunded ETH
*/
function totalRefundedETH() public override view returns (uint256) {
return totalRefundedETH_;
}
/**
* @dev returns the available supply
*/
function availableSupply() public override view returns (uint256) {
uint256 vaultSupply = token_.balanceOf(vaultERC20_);
uint256 allowance = token_.allowance(vaultERC20_, address(this));
return (vaultSupply < allowance) ? vaultSupply : allowance;
}
/* Investor specific attributes */
function investorUnspentETH(address _investor)
public override view returns (uint256)
{
return investorInternal(_investor).unspentETH;
}
function investorInvested(address _investor)
public override view returns (uint256)
{
return investorInternal(_investor).invested;
}
function investorTokens(address _investor) public override view returns (uint256) {
return investorInternal(_investor).tokens;
}
/**
* @dev tokenInvestment
*/
function tokenInvestment(address, uint256 _amount)
public virtual override view returns (uint256)
{
uint256 availableSupplyValue = availableSupply();
uint256 contribution = _amount * priceUnit_ / tokenPrice_;
return (contribution < availableSupplyValue) ? contribution : availableSupplyValue;
}
/**
* @dev refund unspentETH ETH many
*/
function refundManyUnspentETH(address payable[] memory _receivers)
public override onlyOperator returns (bool)
{
for (uint256 i = 0; i < _receivers.length; i++) {
refundUnspentETHInternal(_receivers[i]);
}
return true;
}
/**
* @dev refund unspentETH
*/
function refundUnspentETH() public override returns (bool) {
refundUnspentETHInternal(payable(msg.sender));
return true;
}
/**
* @dev withdraw all ETH funds
*/
function withdrawAllETHFunds() public override onlyOperator returns (bool) {
uint256 balance = address(this).balance;
withdrawETHInternal(balance);
return true;
}
/**
* @dev fund ETH
*/
function fundETH() public override payable onlyOperator {
emit FundETH(msg.value);
}
/**
* @dev investor internal
*/
function investorInternal(address _investor)
internal virtual view returns (Investor storage)
{
return investors[_investor];
}
/**
* @dev eval unspent ETH internal
*/
function evalUnspentETHInternal(
Investor storage _investor, uint256 _investedETH
) internal virtual view returns (uint256)
{
return _investor.unspentETH + msg.value - _investedETH;
}
/**
* @dev eval investment internal
*/
function evalInvestmentInternal(uint256 _tokens)
internal virtual view returns (uint256, uint256)
{
uint256 invested = _tokens * tokenPrice_ / priceUnit_;
return (invested, _tokens);
}
/**
* @dev distribute tokens internal
*/
function distributeTokensInternal(address _investor, uint256 _tokens)
internal virtual
{
require(
token_.transferFrom(vaultERC20_, _investor, _tokens),
"TOS03");
}
/**
* @dev refund unspentETH internal
*/
function refundUnspentETHInternal(address payable _investor) internal virtual {
Investor storage investor = investorInternal(_investor);
require(investor.unspentETH > 0, "TOS04");
uint256 unspentETH = investor.unspentETH;
totalRefundedETH_ = totalRefundedETH_ + unspentETH;
totalUnspentETH_ = totalUnspentETH_ - unspentETH;
investor.unspentETH = 0;
// Multiple sends are required for refundManyUnspentETH
// solhint-disable-next-line multiple-sends
_investor.transfer(unspentETH);
emit RefundETH(_investor, unspentETH);
}
/**
* @dev withdraw ETH internal
*/
function withdrawETHInternal(uint256 _amount) internal virtual {
// Send is used after the ERC20 transfer
// solhint-disable-next-line multiple-sends
vaultETH_.transfer(_amount);
emit WithdrawETH(_amount);
}
/**
* @dev invest internal
*/
function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly)
internal virtual whenNotPaused
{
require(_amount != 0, "TOS05");
Investor storage investor = investorInternal(_investor);
uint256 investment = tokenInvestment(_investor, _amount);
require(investment != 0, "TOS06");
(uint256 invested, uint256 tokens) = evalInvestmentInternal(investment);
if (_exactAmountOnly) {
require(invested == _amount, "TOS07");
} else {
uint256 unspentETH = evalUnspentETHInternal(investor, invested);
totalUnspentETH_ = totalUnspentETH_ - investor.unspentETH + unspentETH;
investor.unspentETH = unspentETH;
}
investor.invested = investor.invested + invested;
investor.tokens = investor.tokens + tokens;
totalRaised_ = totalRaised_ + invested;
totalTokensSold_ = totalTokensSold_ + tokens;
emit Investment(_investor, invested, tokens);
/* Reentrancy risks: No state change must come below */
distributeTokensInternal(_investor, tokens);
uint256 balance = address(this).balance;
uint256 withdrawableETH = balance - totalUnspentETH_;
if (withdrawableETH != 0) {
withdrawETHInternal(withdrawableETH);
}
}
}
| * @dev returns the vault use to/ | function vaultETH() public override view returns (address) {
return vaultETH_;
}
| 2,531,939 | [
1,
6154,
326,
9229,
999,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
9229,
1584,
44,
1435,
1071,
3849,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
9229,
1584,
44,
67,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./FixedQuadraticTokenTimelockUpgradeable.sol";
interface IVotingToken is IERC20 {
function delegate(address delegatee) external;
}
/// @title a timelock for tokens allowing for bulk delegation
/// @author Fei Protocol
/// @notice allows the timelocked tokens to be delegated by the beneficiary while locked
contract FixedQuadraticTimelockedDelegatorUpgradeable is FixedQuadraticTokenTimelockUpgradeable {
/// @notice accept beneficiary role over timelocked TRIBE
function acceptBeneficiary() public override {
_setBeneficiary(msg.sender);
}
/// @notice delegate all held TRIBE to the `to` address
function delegate(address to) public onlyBeneficiary {
IVotingToken(address(lockedToken)).delegate(to);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "./FixedTokenTimelockUpgradeable.sol";
contract FixedQuadraticTokenTimelockUpgradeable is Initializable, FixedTokenTimelockUpgradeable {
function initialize(
address _beneficiary,
uint256 _duration,
address _lockedToken,
uint256 _cliffDuration,
address _clawbackAdmin,
uint256 _lockedAmount,
uint256 _startTime
) external initializer {
__FixedTokenTimelock_init(
_beneficiary,
_duration,
_lockedToken,
_cliffDuration,
_clawbackAdmin,
_lockedAmount
);
if (_startTime != 0) {
startTime = _startTime;
}
}
function _proportionAvailable(
uint256 initialBalance,
uint256 elapsed,
uint256 duration
) internal pure override returns (uint256) {
uint year = 31536000;
if (elapsed <= year) return elapsed / year * initialBalance / 10; // 10% of the initial balance
else if (elapsed <= 2 * year) return elapsed / (2 * year) * initialBalance / 4; // 25%
else if (elapsed <= 3 * year) return elapsed / (3 * year) * initialBalance * 45 / 100; // 45%
else if (elapsed <= 4 * year) return elapsed / (4 * year) * initialBalance * 7 / 10; // 70 %
else if (elapsed < 5 * year) return elapsed / (5 * year) * initialBalance;
else return initialBalance;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* 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 !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./TokenTimelockUpgradeable.sol";
abstract contract FixedTokenTimelockUpgradeable is TokenTimelockUpgradeable {
/// @notice amount of tokens already claimed
uint256 public claimedAmount;
function __FixedTokenTimelock_init(
address _beneficiary,
uint256 _duration,
address _lockedToken,
uint256 _cliffDuration,
address _clawbackAdmin,
uint256 _lockedAmount
) internal onlyInitializing {
__TokenTimelock_init(
_beneficiary,
_duration,
_cliffDuration,
_lockedToken,
_clawbackAdmin
);
require(_lockedAmount > 0, "FixedTokenTimelock: no amount locked");
initialBalance = _lockedAmount;
}
// Prevents incoming LP tokens from messing up calculations
modifier balanceCheck() override {
_;
}
/// @notice amount of tokens released to beneficiary
function alreadyReleasedAmount() public view override returns (uint256) {
return claimedAmount;
}
function _release(address to, uint256 amount) internal override {
claimedAmount = claimedAmount + amount;
lockedToken.transfer(to, amount);
emit Release(beneficiary, to, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
// Inspired by OpenZeppelin TokenTimelock contract
// Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/TokenTimelock.sol
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../utils/TimedUpgradeable.sol";
import "./ITokenTimelock.sol";
abstract contract TokenTimelockUpgradeable is Initializable, ITokenTimelock, TimedUpgradeable {
/// @notice ERC20 basic token contract being held in timelock
IERC20 public override lockedToken;
/// @notice beneficiary of tokens after they are released
address public override beneficiary;
/// @notice pending beneficiary appointed by current beneficiary
address public override pendingBeneficiary;
/// @notice initial balance of lockedToken
uint256 public override initialBalance;
uint256 internal lastBalance;
/// @notice number of seconds before releasing is allowed
uint256 public cliffSeconds;
address public clawbackAdmin;
function __TokenTimelock_init(
address _beneficiary,
uint256 _duration,
uint256 _cliffSeconds,
address _lockedToken,
address _clawbackAdmin
) internal onlyInitializing {
__Timed_init_unchained(_duration);
__TokenTimelock_init_unchained(
_beneficiary,
_duration,
_cliffSeconds,
_lockedToken,
_clawbackAdmin
);
}
function __TokenTimelock_init_unchained(
address _beneficiary,
uint256 _duration,
uint256 _cliffSeconds,
address _lockedToken,
address _clawbackAdmin
) internal onlyInitializing {
require(_duration != 0, "TokenTimelock: duration is 0");
require(
_beneficiary != address(0),
"TokenTimelock: Beneficiary must not be 0 address"
);
beneficiary = _beneficiary;
_initTimed();
_setLockedToken(_lockedToken);
cliffSeconds = _cliffSeconds;
clawbackAdmin = _clawbackAdmin;
}
// Prevents incoming LP tokens from messing up calculations
modifier balanceCheck() virtual {
if (totalToken() > lastBalance) {
uint256 delta = totalToken() - lastBalance;
initialBalance = initialBalance + delta;
}
_;
lastBalance = totalToken();
}
modifier onlyBeneficiary() {
require(
msg.sender == beneficiary,
"TokenTimelock: Caller is not a beneficiary"
);
_;
}
/// @notice releases `amount` unlocked tokens to address `to`
function release(address to, uint256 amount) external override onlyBeneficiary balanceCheck {
require(amount != 0, "TokenTimelock: no amount desired");
require(passedCliff(), "TokenTimelock: Cliff not passed");
uint256 available = availableForRelease();
require(amount <= available, "TokenTimelock: not enough released tokens");
_release(to, amount);
}
/// @notice releases maximum unlocked tokens to address `to`
function releaseMax(address to) external override onlyBeneficiary balanceCheck {
require(passedCliff(), "TokenTimelock: Cliff not passed");
_release(to, availableForRelease());
}
/// @notice the total amount of tokens held by timelock
function totalToken() public view override virtual returns (uint256) {
return lockedToken.balanceOf(address(this));
}
/// @notice amount of tokens released to beneficiary
function alreadyReleasedAmount() public view override virtual returns (uint256) {
return initialBalance - totalToken();
}
/// @notice amount of held tokens unlocked and available for release
function availableForRelease() public view override returns (uint256) {
uint256 elapsed = timeSinceStart();
uint256 totalAvailable = _proportionAvailable(initialBalance, elapsed, duration);
uint256 netAvailable = totalAvailable - alreadyReleasedAmount();
return netAvailable;
}
/// @notice current beneficiary can appoint new beneficiary, which must be accepted
function setPendingBeneficiary(address _pendingBeneficiary)
public
override
onlyBeneficiary
{
pendingBeneficiary = _pendingBeneficiary;
emit PendingBeneficiaryUpdate(_pendingBeneficiary);
}
/// @notice pending beneficiary accepts new beneficiary
function acceptBeneficiary() public override virtual {
_setBeneficiary(msg.sender);
}
function clawback() public balanceCheck {
require(msg.sender == clawbackAdmin, "TokenTimelock: Only clawbackAdmin");
if (passedCliff()) {
_release(beneficiary, availableForRelease());
}
_release(clawbackAdmin, totalToken());
}
function passedCliff() public view returns (bool) {
return timeSinceStart() >= cliffSeconds;
}
function _proportionAvailable(uint256 initialBalance, uint256 elapsed, uint256 duration) internal pure virtual returns (uint256);
function _setBeneficiary(address newBeneficiary) internal {
require(
newBeneficiary == pendingBeneficiary,
"TokenTimelock: Caller is not pending beneficiary"
);
beneficiary = newBeneficiary;
emit BeneficiaryUpdate(newBeneficiary);
pendingBeneficiary = address(0);
}
function _setLockedToken(address tokenAddress) internal {
lockedToken = IERC20(tokenAddress);
}
function _release(address to, uint256 amount) internal virtual {
lockedToken.transfer(to, amount);
emit Release(beneficiary, to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/// @title an abstract contract for timed events
/// @author Fei Protocol
abstract contract TimedUpgradeable is Initializable {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 oldDuration, uint256 newDuration);
event TimerReset(uint256 startTime);
function __Timed_init(uint256 _duration) internal onlyInitializing {
__Timed_init_unchained(_duration);
}
function __Timed_init_unchained(uint256 _duration) internal onlyInitializing {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
startTime = block.timestamp;
emit TimerReset(block.timestamp);
}
function _setDuration(uint256 newDuration) internal {
require(newDuration != 0, "Timed: zero duration");
uint256 oldDuration = duration;
duration = newDuration;
emit DurationUpdate(oldDuration, newDuration);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title TokenTimelock interface
/// @author Fei Protocol
interface ITokenTimelock {
// ----------- Events -----------
event Release(address indexed _beneficiary, address indexed _recipient, uint256 _amount);
event BeneficiaryUpdate(address indexed _beneficiary);
event PendingBeneficiaryUpdate(address indexed _pendingBeneficiary);
// ----------- State changing api -----------
function release(address to, uint256 amount) external;
function releaseMax(address to) external;
function setPendingBeneficiary(address _pendingBeneficiary) external;
function acceptBeneficiary() external;
// ----------- Getters -----------
function lockedToken() external view returns (IERC20);
function beneficiary() external view returns (address);
function pendingBeneficiary() external view returns (address);
function initialBalance() external view returns (uint256);
function availableForRelease() external view returns (uint256);
function totalToken() external view returns(uint256);
function alreadyReleasedAmount() external view returns (uint256);
} | @notice amount of tokens released to beneficiary | function alreadyReleasedAmount() public view override virtual returns (uint256) {
return initialBalance - totalToken();
}
| 10,167,655 | [
1,
8949,
434,
2430,
15976,
358,
27641,
74,
14463,
814,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1818,
26363,
6275,
1435,
1071,
1476,
3849,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2172,
13937,
300,
2078,
1345,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
// 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;
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract APAD is ERC20, Ownable {
using SafeMath for uint256;
modifier lockSwap {
_inSwap = true;
_;
_inSwap = false;
}
modifier liquidityAdd {
_inLiquidityAdd = true;
_;
_inLiquidityAdd = false;
}
uint256 public constant MAX_SUPPLY = 1_000_000_000 ether;
uint256 public constant BPS_DENOMINATOR = 10_000;
/// @notice Max transfer rate in BPS. Initialized at 0.4%
uint256 public maxTransfer;
/// @notice Cooldown in seconds
uint256 public cooldown = 20;
/// @notice Buy tax0 in BPS
uint256 public buyTax0 = 1125;
/// @notice Sell tax0 in BPS
uint256 public sellTax0 = 1875;
/// @notice Buy tax1 in BPS
uint256 public buyTax1 = 375;
/// @notice Sell tax1 in BPS
uint256 public sellTax1 = 625;
/// @notice Contract APAD balance threshold before `_swap` is invoked
uint256 public minTokenBalance = 1000 ether;
bool public swapFees = true;
/// @notice tokens that are allocated for tax0 tax
uint256 public totalTax0;
/// @notice tokens that are allocated for tax1 tax
uint256 public totalTax1;
/// @notice address that tax0 is sent to
address payable public tax0Wallet;
/// @notice address that tax1 is sent to
address payable public tax1Wallet;
uint256 internal _totalSupply = 0;
IUniswapV2Router02 internal _router = IUniswapV2Router02(address(0));
address internal _pair;
bool internal _inSwap = false;
bool internal _inLiquidityAdd = false;
bool public tradingActive = false;
mapping(address => uint256) private _balances;
mapping(address => bool) public taxExcluded;
mapping(address => uint256) public lastBuy;
event Tax0WalletChanged(address previousWallet, address nextWallet);
event Tax1WalletChanged(address previousWallet, address nextWallet);
event BuyTax0Changed(uint256 previousTax, uint256 nextTax);
event SellTax0Changed(uint256 previousTax, uint256 nextTax);
event BuyTax1Changed(uint256 previousTax, uint256 nextTax);
event SellTax1Changed(uint256 previousTax, uint256 nextTax);
event MinTokenBalanceChanged(uint256 previousMin, uint256 nextMin);
event Tax0Rescued(uint256 amount);
event Tax1Rescued(uint256 amount);
event TradingActiveChanged(bool enabled);
event TaxExclusionChanged(address user, bool taxExcluded);
event MaxTransferChanged(uint256 previousMax, uint256 nextMax);
event SwapFeesChanged(bool enabled);
event CooldownChanged(uint256 previousCooldown, uint256 nextCooldown);
constructor(
address _uniswapFactory,
address _uniswapRouter,
uint256 _maxTransfer,
address payable _tax0Wallet,
address payable _tax1Wallet
) ERC20("Alpha Pad", "APAD") Ownable() {
taxExcluded[owner()] = true;
taxExcluded[address(0)] = true;
taxExcluded[_tax0Wallet] = true;
taxExcluded[_tax1Wallet] = true;
taxExcluded[address(this)] = true;
maxTransfer = _maxTransfer;
tax0Wallet = _tax0Wallet;
tax1Wallet = _tax1Wallet;
_router = IUniswapV2Router02(_uniswapRouter);
IUniswapV2Factory uniswapContract = IUniswapV2Factory(_uniswapFactory);
_pair = uniswapContract.createPair(address(this), _router.WETH());
}
/// @notice Change the address of the buyback wallet
/// @param _tax0Wallet The new address of the buyback wallet
function setTax0Wallet(address payable _tax0Wallet) external onlyOwner() {
emit Tax0WalletChanged(tax0Wallet, _tax0Wallet);
tax0Wallet = _tax0Wallet;
}
/// @notice Change the address of the tax1 wallet
/// @param _tax1Wallet The new address of the tax1 wallet
function setTax1Wallet(address payable _tax1Wallet) external onlyOwner() {
emit Tax1WalletChanged(tax1Wallet, _tax1Wallet);
tax1Wallet = _tax1Wallet;
}
/// @notice Change the buy tax0 rate
/// @param _buyTax0 The new buy tax0 rate
function setBuyTax0(uint256 _buyTax0) external onlyOwner() {
require(_buyTax0 <= BPS_DENOMINATOR, "_buyTax0 cannot exceed BPS_DENOMINATOR");
emit BuyTax0Changed(buyTax0, _buyTax0);
buyTax0 = _buyTax0;
}
/// @notice Change the sell tax0 rate
/// @param _sellTax0 The new sell tax0 rate
function setSellTax0(uint256 _sellTax0) external onlyOwner() {
require(_sellTax0 <= BPS_DENOMINATOR, "_sellTax0 cannot exceed BPS_DENOMINATOR");
emit SellTax0Changed(sellTax0, _sellTax0);
sellTax0 = _sellTax0;
}
/// @notice Change the buy tax1 rate
/// @param _buyTax1 The new tax1 rate
function setBuyTax1(uint256 _buyTax1) external onlyOwner() {
require(_buyTax1 <= BPS_DENOMINATOR, "_buyTax1 cannot exceed BPS_DENOMINATOR");
emit BuyTax1Changed(buyTax1, _buyTax1);
buyTax1 = _buyTax1;
}
/// @notice Change the buy tax1 rate
/// @param _sellTax1 The new tax1 rate
function setSellTax1(uint256 _sellTax1) external onlyOwner() {
require(_sellTax1 <= BPS_DENOMINATOR, "_sellTax1 cannot exceed BPS_DENOMINATOR");
emit SellTax1Changed(sellTax1, _sellTax1);
sellTax1 = _sellTax1;
}
/// @notice Change the minimum contract APAD balance before `_swap` gets invoked
/// @param _minTokenBalance The new minimum balance
function setMinTokenBalance(uint256 _minTokenBalance) external onlyOwner() {
emit MinTokenBalanceChanged(minTokenBalance, _minTokenBalance);
minTokenBalance = _minTokenBalance;
}
/// @notice Change the cooldown for buys
/// @param _cooldown The new cooldown in seconds
function setCooldown(uint256 _cooldown) external onlyOwner() {
emit CooldownChanged(cooldown, _cooldown);
cooldown = _cooldown;
}
/// @notice Rescue APAD from the tax0 amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of APAD to rescue
/// @param _recipient The recipient of the rescued APAD
function rescueTax0Tokens(uint256 _amount, address _recipient) external onlyOwner() {
require(_amount <= totalTax0, "Amount cannot be greater than totalTax0");
_rawTransfer(address(this), _recipient, _amount);
emit Tax0Rescued(_amount);
totalTax0 -= _amount;
}
/// @notice Rescue APAD from the tax1 amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of APAD to rescue
/// @param _recipient The recipient of the rescued APAD
function rescueTax1Tokens(uint256 _amount, address _recipient) external onlyOwner() {
require(_amount <= totalTax1, "Amount cannot be greater than totalTax1");
_rawTransfer(address(this), _recipient, _amount);
emit Tax1Rescued(_amount);
totalTax1 -= _amount;
}
function addLiquidity(uint256 tokens) external payable onlyOwner() liquidityAdd {
_mint(address(this), tokens);
_approve(address(this), address(_router), tokens);
_router.addLiquidityETH{value: msg.value}(
address(this),
tokens,
0,
0,
owner(),
// solhint-disable-next-line not-rely-on-time
block.timestamp
);
}
/// @notice Enables or disables trading on Uniswap
function setTradingActive(bool _tradingActive) external onlyOwner {
tradingActive = _tradingActive;
emit TradingActiveChanged(_tradingActive);
}
/// @notice Updates tax exclusion status
/// @param _account Account to update the tax exclusion status of
/// @param _taxExcluded If true, exclude taxes for this user
function setTaxExcluded(address _account, bool _taxExcluded) public onlyOwner() {
taxExcluded[_account] = _taxExcluded;
emit TaxExclusionChanged(_account, _taxExcluded);
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function _addBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] + amount;
}
function _subtractBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] - amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (taxExcluded[sender] || taxExcluded[recipient]) {
_rawTransfer(sender, recipient, amount);
return;
}
uint256 maxTxAmount = totalSupply().mul(maxTransfer).div(BPS_DENOMINATOR);
require(amount <= maxTxAmount || _inLiquidityAdd || _inSwap || recipient == address(_router), "Exceeds max transaction amount");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokenBalance;
if(contractTokenBalance >= maxTxAmount) {
contractTokenBalance = maxTxAmount;
}
if (
overMinTokenBalance &&
!_inSwap &&
sender != _pair &&
swapFees
) {
_swap(contractTokenBalance);
}
uint256 send = amount;
uint256 tax0;
uint256 tax1;
if (sender == _pair) {
require(tradingActive, "Trading is not yet active");
if (cooldown > 0) {
require(lastBuy[recipient] + cooldown <= block.timestamp, "Cooldown still active");
lastBuy[recipient] = block.timestamp;
}
(
send,
tax0,
tax1
) = _getTaxAmounts(amount, true);
} else if (recipient == _pair) {
require(tradingActive, "Trading is not yet active");
(
send,
tax0,
tax1
) = _getTaxAmounts(amount, false);
}
_rawTransfer(sender, recipient, send);
_takeTaxes(sender, tax0, tax1);
}
/// @notice Perform a Uniswap v2 swap from APAD to ETH and handle tax distribution
/// @param amount The amount of APAD to swap in wei
/// @dev `amount` is always <= this contract's ETH balance. Calculate and distribute taxes
function _swap(uint256 amount) internal lockSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _router.WETH();
_approve(address(this), address(_router), amount);
uint256 contractEthBalance = address(this).balance;
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this),
block.timestamp
);
uint256 tradeValue = address(this).balance - contractEthBalance;
uint256 totalTaxes = totalTax0.add(totalTax1);
uint256 tax0Amount = amount.mul(totalTax0).div(totalTaxes);
uint256 tax1Amount = amount.mul(totalTax1).div(totalTaxes);
uint256 tax0Eth = tradeValue.mul(totalTax0).div(totalTaxes);
uint256 tax1Eth = tradeValue.mul(totalTax1).div(totalTaxes);
if (tax0Eth > 0) {
tax0Wallet.transfer(tax0Eth);
}
if (tax1Eth > 0) {
tax1Wallet.transfer(tax1Eth);
}
totalTax0 = totalTax0.sub(tax0Amount);
totalTax1 = totalTax1.sub(tax1Amount);
}
function swapAll() external {
uint256 maxTxAmount = totalSupply().mul(maxTransfer).div(BPS_DENOMINATOR);
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxTxAmount)
{
contractTokenBalance = maxTxAmount;
}
if (
!_inSwap
) {
_swap(contractTokenBalance);
}
}
function withdrawAll() external onlyOwner() {
payable(owner()).transfer(address(this).balance);
}
/// @notice Transfers APAD from an account to this contract for taxes
/// @param _account The account to transfer APAD from
/// @param _tax0Amount The amount of tax0 tax to transfer
/// @param _tax1Amount The amount of tax1 tax to transfer
function _takeTaxes(
address _account,
uint256 _tax0Amount,
uint256 _tax1Amount
) internal {
require(_account != address(0), "taxation from the zero address");
uint256 totalAmount = _tax0Amount.add(_tax1Amount);
_rawTransfer(_account, address(this), totalAmount);
totalTax0 += _tax0Amount;
totalTax1 += _tax1Amount;
}
/// @notice Get a breakdown of send and tax amounts
/// @param amount The amount to tax in wei
/// @return send The raw amount to send
/// @return tax0 The raw tax0 tax amount
/// @return tax1 The raw tax1 tax amount
function _getTaxAmounts(uint256 amount, bool buying)
internal
view
returns (
uint256 send,
uint256 tax0,
uint256 tax1
)
{
if (buying) {
tax0 = amount.mul(buyTax0).div(BPS_DENOMINATOR);
tax1 = amount.mul(buyTax1).div(BPS_DENOMINATOR);
} else {
tax0 = amount.mul(sellTax0).div(BPS_DENOMINATOR);
tax1 = amount.mul(sellTax1).div(BPS_DENOMINATOR);
}
send = amount.sub(tax0).sub(tax1);
}
// modified from OpenZeppelin ERC20
function _rawTransfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
uint256 senderBalance = balanceOf(sender);
require(senderBalance >= amount, "transfer amount exceeds balance");
unchecked {
_subtractBalance(sender, amount);
}
_addBalance(recipient, amount);
emit Transfer(sender, recipient, amount);
}
/// @notice Updates the max amount allowed to transfer
/// @param _maxTransfer The new max transfer rate
function setMaxTransfer(uint256 _maxTransfer) external onlyOwner() {
require(_maxTransfer <= BPS_DENOMINATOR, "_maxTransfer cannot exceed BPS_DENOMINATOR");
emit MaxTransferChanged(maxTransfer, _maxTransfer);
maxTransfer = _maxTransfer;
}
/// @notice Enable or disable whether swap occurs during `_transfer`
/// @param _swapFees If true, enables swap during `_transfer`
function setSwapFees(bool _swapFees) external onlyOwner() {
swapFees = _swapFees;
emit SwapFeesChanged(_swapFees);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function _mint(address account, uint256 amount) internal override {
require(_totalSupply.add(amount) <= MAX_SUPPLY, "Max supply exceeded");
_totalSupply += amount;
_addBalance(account, amount);
emit Transfer(address(0), account, amount);
}
function mint(address account, uint256 amount) external onlyOwner() {
_mint(account, amount);
}
function airdrop(address[] memory accounts, uint256[] memory amounts) external onlyOwner() {
require(accounts.length == amounts.length, "array lengths must match");
for (uint256 i = 0; i < accounts.length; i++) {
_mint(accounts[i], amounts[i]);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
} | @notice Sell tax1 in BPS | uint256 public sellTax1 = 625;
| 1,419,918 | [
1,
55,
1165,
5320,
21,
316,
605,
5857,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
357,
80,
7731,
21,
273,
1666,
2947,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
// File: contracts/Ownable.sol
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @dev The Ownable contract has an owner address, and provides basic
/// authorization control functions, this simplifies the implementation of
/// "user permissions".
contract Ownable
{
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev The Ownable constructor sets the original `owner` of the contract
/// to the sender.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// File: contracts/Claimable.sol
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/ERC20.sol
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
view
virtual
returns (uint);
function balanceOf(
address who
)
public
view
virtual
returns (uint);
function allowance(
address owner,
address spender
)
public
view
virtual
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// File: contracts/MathUint.sol
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// File: contracts/BaseTokenOwnershipPlan.sol
/// @title EmployeeTokenOwnershipPlan
/// @author Freeman Zhong - <[email protected]>
/// added at 2021-02-19
abstract contract BaseTokenOwnershipPlan is Claimable
{
using MathUint for uint;
struct Record {
uint lastWithdrawTime;
uint rewarded;
uint withdrawn;
}
uint public constant vestPeriod = 2 * 365 days;
address public constant lrcAddress = 0xBBbbCA6A901c926F240b89EacB641d8Aec7AEafD;
uint public totalReward;
uint public vestStart;
mapping (address => Record) public records;
event Withdrawal(
address indexed transactor,
address indexed member,
uint amount
);
event MemberAddressChanged(
address oldAddress,
address newAddress
);
function withdrawFor(address recipient)
external
{
_withdraw(recipient);
}
function updateRecipient(address oldRecipient, address newRecipient)
external
{
require(canChangeAddressFor(oldRecipient), "UNAUTHORIZED");
require(newRecipient != address(0), "INVALID_ADDRESS");
require(records[newRecipient].rewarded == 0, "INVALID_NEW_RECIPIENT");
Record storage r = records[oldRecipient];
require(r.rewarded > 0, "INVALID_OLD_RECIPIENT");
records[newRecipient] = r;
delete records[oldRecipient];
emit MemberAddressChanged(oldRecipient, newRecipient);
}
function vested(address recipient)
public
view
returns(uint)
{
if (block.timestamp.sub(vestStart) < vestPeriod) {
return records[recipient].rewarded.mul(block.timestamp.sub(vestStart)) / vestPeriod;
} else {
return records[recipient].rewarded;
}
}
function withdrawable(address recipient)
public
view
returns(uint)
{
return vested(recipient).sub(records[recipient].withdrawn);
}
function _withdraw(address recipient)
internal
{
uint amount = withdrawable(recipient);
require(amount > 0, "INVALID_AMOUNT");
Record storage r = records[recipient];
r.lastWithdrawTime = block.timestamp;
r.withdrawn = r.withdrawn.add(amount);
require(ERC20(lrcAddress).transfer(recipient, amount), "transfer failed");
emit Withdrawal(msg.sender, recipient, amount);
}
receive() external payable {
require(msg.value == 0, "INVALID_VALUE");
_withdraw(msg.sender);
}
function collect()
external
onlyOwner
{
require(block.timestamp > vestStart + vestPeriod + 60 days, "TOO_EARLY");
uint amount = ERC20(lrcAddress).balanceOf(address(this));
require(ERC20(lrcAddress).transfer(msg.sender, amount), "transfer failed");
}
function canChangeAddressFor(address who)
internal
view
virtual
returns (bool);
}
// File: contracts/CancellableEmployeeTokenOwnershipPlan.sol
/// @title EmployeeTokenOwnershipPlan2
/// added at 2021-02-14
/// @author Freeman Zhong - <[email protected]>
contract CancellableEmployeeTokenOwnershipPlan is BaseTokenOwnershipPlan
{
using MathUint for uint;
constructor()
{
owner = 0x96f16FdB8Cd37C02DEeb7025C1C7618E1bB34d97;
address payable[35] memory _members = [
0xFF6f7B2afdd33671503705098dd3c4c26a0F0705,
0xf493af7DFd0e47869Aac4770B2221a259CA77Ac8,
0xf21e66578372Ea62BCb0D1cDfC070f231CF56898,
0xEBE85822e75D2B4716e228818B54154E4AfFD202,
0xeB4c50dF06cEb2Ea700ea127eA589A99a3aAe1Ec,
0xe0807d8E14F2BCbF3Cc58637259CCF3fDd1D3ce5,
0xD984D096B4bF9DCF5fd75D9cBaf052D00EBe74c4,
0xd3725C997B580E36707f73880aC006B6757b5009,
0xBc5F996840118B580C4452440351b601862c5672,
0xad05c57e06a80b8EC92383b3e10Fea0E2b4e571D,
0xa26cFCeCb07e401547be07eEe26E6FD608f77d1a,
0x933650184994CFce9D64A9F3Ed14F1Fd017fF89A,
0x813C12326A0E8C2aC91d584f025E50072CDb4467,
0x7F81D533B2ea31BE2591d89394ADD9A12499ff17,
0x7F6Dd0c1BeB26CFf8ABA5B020E78D7C0Ed54B8Cc,
0x7b3B1F252169Ff83E3E91106230c36bE672aFdE3,
0x7809D08edBBBC401c430e5D3862a1Fdfcb8094A2,
0x7154a02BA6eEaB9300D056e25f3EEA3481680f87,
0x650EACf9AD1576680f1af6eC6cC598A484d796Ad,
0x5a092E52B9b3109372B9905Fa5c0655417F0f1a5,
0x5a03a928b332EC269f68684A8e9c1881b4Da5f3d,
0x55634e271BCa62dDFb9B5f7eae19f3Ae94Fb96b7,
0x4c381276F4847255C675Eab90c3409FA2fce68bC,
0x4bA63ac57b45087d03Abfd8E98987705Fa56B1ab,
0x474A2F53D11c73Ef2343322d69dCAE93cd63Dd9e,
0x41cDd7034AD6b2a5d24397189802048E97b6532D,
0x33CDbeB3e060bf6973e28492BE3D469C05D32786,
0x2a791a837D70E6D6e35073Dd61a9Af878Ac231A5,
0x2234C96681E9533FDfD122baCBBc634EfbafA0F0,
0x21870650F40Fe8249DECc96525249a43829E9A32,
0x1F28F10176F89F4E9985873B84d14e75751BB3D1,
0x11a8632b5089c6a061760F0b03285e2cC1388E36,
0x10Bd72a6AfbF8860ec90f7aeCdB8e937a758f351,
0x07A7191de1BA70dBe875F12e744B020416a5712b,
0x067eceAd820BC54805A2412B06946b184d11CB4b
];
uint80[35] memory _amounts = [
187520 ether,
256002 ether,
538180 ether,
340060 ether,
289314 ether,
176782 ether,
308310 ether,
398740 ether,
31254 ether,
82284 ether,
435961 ether,
459366 ether,
453078 ether,
150296 ether,
500972 ether,
375040 ether,
283528 ether,
155765 ether,
316840 ether,
38873 ether,
89970 ether,
549381 ether,
150834 ether,
501058 ether,
77746 ether,
145641 ether,
173213 ether,
573800 ether,
539572 ether,
110258 ether,
58022 ether,
398740 ether,
561054 ether,
221724 ether,
485991 ether
];
uint _totalReward = 10415169 ether;
vestStart = block.timestamp;
for (uint i = 0; i < _members.length; i++) {
require(records[_members[i]].rewarded == 0, "DUPLICATED_MEMBER");
Record memory record = Record(block.timestamp, _amounts[i], 0);
records[_members[i]] = record;
totalReward = totalReward.add(_amounts[i]);
}
require(_totalReward == totalReward, "VALUE_MISMATCH");
}
function canChangeAddressFor(address who)
internal
view
override
returns (bool) {
return msg.sender == who || msg.sender == owner;
}
} | File: contracts/CancellableEmployeeTokenOwnershipPlan.sol @title EmployeeTokenOwnershipPlan2 added at 2021-02-14 @author Freeman Zhong - <[email protected]> | {
using MathUint for uint;
constructor()
function canChangeAddressFor(address who)
internal
view
virtual
returns (bool);
}
contract CancellableEmployeeTokenOwnershipPlan is BaseTokenOwnershipPlan
{
owner = 0x96f16FdB8Cd37C02DEeb7025C1C7618E1bB34d97;
address payable[35] memory _members = [
0xFF6f7B2afdd33671503705098dd3c4c26a0F0705,
0xf493af7DFd0e47869Aac4770B2221a259CA77Ac8,
0xf21e66578372Ea62BCb0D1cDfC070f231CF56898,
0xEBE85822e75D2B4716e228818B54154E4AfFD202,
0xeB4c50dF06cEb2Ea700ea127eA589A99a3aAe1Ec,
0xe0807d8E14F2BCbF3Cc58637259CCF3fDd1D3ce5,
0xD984D096B4bF9DCF5fd75D9cBaf052D00EBe74c4,
0xd3725C997B580E36707f73880aC006B6757b5009,
0xBc5F996840118B580C4452440351b601862c5672,
0xad05c57e06a80b8EC92383b3e10Fea0E2b4e571D,
0xa26cFCeCb07e401547be07eEe26E6FD608f77d1a,
0x933650184994CFce9D64A9F3Ed14F1Fd017fF89A,
0x813C12326A0E8C2aC91d584f025E50072CDb4467,
0x7F81D533B2ea31BE2591d89394ADD9A12499ff17,
0x7F6Dd0c1BeB26CFf8ABA5B020E78D7C0Ed54B8Cc,
0x7b3B1F252169Ff83E3E91106230c36bE672aFdE3,
0x7809D08edBBBC401c430e5D3862a1Fdfcb8094A2,
0x7154a02BA6eEaB9300D056e25f3EEA3481680f87,
0x650EACf9AD1576680f1af6eC6cC598A484d796Ad,
0x5a092E52B9b3109372B9905Fa5c0655417F0f1a5,
0x5a03a928b332EC269f68684A8e9c1881b4Da5f3d,
0x55634e271BCa62dDFb9B5f7eae19f3Ae94Fb96b7,
0x4c381276F4847255C675Eab90c3409FA2fce68bC,
0x4bA63ac57b45087d03Abfd8E98987705Fa56B1ab,
0x474A2F53D11c73Ef2343322d69dCAE93cd63Dd9e,
0x41cDd7034AD6b2a5d24397189802048E97b6532D,
0x33CDbeB3e060bf6973e28492BE3D469C05D32786,
0x2a791a837D70E6D6e35073Dd61a9Af878Ac231A5,
0x2234C96681E9533FDfD122baCBBc634EfbafA0F0,
0x21870650F40Fe8249DECc96525249a43829E9A32,
0x1F28F10176F89F4E9985873B84d14e75751BB3D1,
0x11a8632b5089c6a061760F0b03285e2cC1388E36,
0x10Bd72a6AfbF8860ec90f7aeCdB8e937a758f351,
0x07A7191de1BA70dBe875F12e744B020416a5712b,
0x067eceAd820BC54805A2412B06946b184d11CB4b
];
uint80[35] memory _amounts = [
187520 ether,
256002 ether,
538180 ether,
340060 ether,
289314 ether,
176782 ether,
308310 ether,
398740 ether,
31254 ether,
82284 ether,
435961 ether,
459366 ether,
453078 ether,
150296 ether,
500972 ether,
375040 ether,
283528 ether,
155765 ether,
316840 ether,
38873 ether,
89970 ether,
549381 ether,
150834 ether,
501058 ether,
77746 ether,
145641 ether,
173213 ether,
573800 ether,
539572 ether,
110258 ether,
58022 ether,
398740 ether,
561054 ether,
221724 ether,
485991 ether
];
uint _totalReward = 10415169 ether;
vestStart = block.timestamp;
for (uint i = 0; i < _members.length; i++) {
require(records[_members[i]].rewarded == 0, "DUPLICATED_MEMBER");
Record memory record = Record(block.timestamp, _amounts[i], 0);
records[_members[i]] = record;
totalReward = totalReward.add(_amounts[i]);
}
require(_totalReward == totalReward, "VALUE_MISMATCH");
}
function canChangeAddressFor(address who)
internal
view
virtual
returns (bool);
}
contract CancellableEmployeeTokenOwnershipPlan is BaseTokenOwnershipPlan
{
owner = 0x96f16FdB8Cd37C02DEeb7025C1C7618E1bB34d97;
address payable[35] memory _members = [
0xFF6f7B2afdd33671503705098dd3c4c26a0F0705,
0xf493af7DFd0e47869Aac4770B2221a259CA77Ac8,
0xf21e66578372Ea62BCb0D1cDfC070f231CF56898,
0xEBE85822e75D2B4716e228818B54154E4AfFD202,
0xeB4c50dF06cEb2Ea700ea127eA589A99a3aAe1Ec,
0xe0807d8E14F2BCbF3Cc58637259CCF3fDd1D3ce5,
0xD984D096B4bF9DCF5fd75D9cBaf052D00EBe74c4,
0xd3725C997B580E36707f73880aC006B6757b5009,
0xBc5F996840118B580C4452440351b601862c5672,
0xad05c57e06a80b8EC92383b3e10Fea0E2b4e571D,
0xa26cFCeCb07e401547be07eEe26E6FD608f77d1a,
0x933650184994CFce9D64A9F3Ed14F1Fd017fF89A,
0x813C12326A0E8C2aC91d584f025E50072CDb4467,
0x7F81D533B2ea31BE2591d89394ADD9A12499ff17,
0x7F6Dd0c1BeB26CFf8ABA5B020E78D7C0Ed54B8Cc,
0x7b3B1F252169Ff83E3E91106230c36bE672aFdE3,
0x7809D08edBBBC401c430e5D3862a1Fdfcb8094A2,
0x7154a02BA6eEaB9300D056e25f3EEA3481680f87,
0x650EACf9AD1576680f1af6eC6cC598A484d796Ad,
0x5a092E52B9b3109372B9905Fa5c0655417F0f1a5,
0x5a03a928b332EC269f68684A8e9c1881b4Da5f3d,
0x55634e271BCa62dDFb9B5f7eae19f3Ae94Fb96b7,
0x4c381276F4847255C675Eab90c3409FA2fce68bC,
0x4bA63ac57b45087d03Abfd8E98987705Fa56B1ab,
0x474A2F53D11c73Ef2343322d69dCAE93cd63Dd9e,
0x41cDd7034AD6b2a5d24397189802048E97b6532D,
0x33CDbeB3e060bf6973e28492BE3D469C05D32786,
0x2a791a837D70E6D6e35073Dd61a9Af878Ac231A5,
0x2234C96681E9533FDfD122baCBBc634EfbafA0F0,
0x21870650F40Fe8249DECc96525249a43829E9A32,
0x1F28F10176F89F4E9985873B84d14e75751BB3D1,
0x11a8632b5089c6a061760F0b03285e2cC1388E36,
0x10Bd72a6AfbF8860ec90f7aeCdB8e937a758f351,
0x07A7191de1BA70dBe875F12e744B020416a5712b,
0x067eceAd820BC54805A2412B06946b184d11CB4b
];
uint80[35] memory _amounts = [
187520 ether,
256002 ether,
538180 ether,
340060 ether,
289314 ether,
176782 ether,
308310 ether,
398740 ether,
31254 ether,
82284 ether,
435961 ether,
459366 ether,
453078 ether,
150296 ether,
500972 ether,
375040 ether,
283528 ether,
155765 ether,
316840 ether,
38873 ether,
89970 ether,
549381 ether,
150834 ether,
501058 ether,
77746 ether,
145641 ether,
173213 ether,
573800 ether,
539572 ether,
110258 ether,
58022 ether,
398740 ether,
561054 ether,
221724 ether,
485991 ether
];
uint _totalReward = 10415169 ether;
vestStart = block.timestamp;
for (uint i = 0; i < _members.length; i++) {
require(records[_members[i]].rewarded == 0, "DUPLICATED_MEMBER");
Record memory record = Record(block.timestamp, _amounts[i], 0);
records[_members[i]] = record;
totalReward = totalReward.add(_amounts[i]);
}
require(_totalReward == totalReward, "VALUE_MISMATCH");
}
function canChangeAddressFor(address who)
internal
view
override
returns (bool) {
return msg.sender == who || msg.sender == owner;
}
} | 6,910,926 | [
1,
812,
30,
20092,
19,
2568,
3855,
429,
41,
27520,
1345,
5460,
12565,
5365,
18,
18281,
225,
512,
27520,
1345,
5460,
12565,
5365,
22,
3096,
622,
26599,
21,
17,
3103,
17,
3461,
225,
478,
266,
351,
304,
2285,
76,
932,
300,
411,
79,
932,
549,
539,
36,
6498,
8022,
18,
3341,
34,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1450,
2361,
5487,
364,
2254,
31,
203,
203,
565,
3885,
1435,
203,
565,
445,
848,
3043,
1887,
1290,
12,
2867,
10354,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
6430,
1769,
203,
97,
203,
203,
203,
203,
203,
203,
203,
16351,
4480,
3855,
429,
41,
27520,
1345,
5460,
12565,
5365,
353,
3360,
1345,
5460,
12565,
5365,
203,
565,
288,
203,
3639,
3410,
273,
374,
92,
10525,
74,
2313,
27263,
38,
28,
19728,
6418,
39,
3103,
1639,
24008,
7301,
2947,
39,
21,
39,
6669,
2643,
41,
21,
70,
38,
5026,
72,
10580,
31,
203,
203,
3639,
1758,
8843,
429,
63,
4763,
65,
3778,
389,
7640,
273,
306,
203,
5411,
374,
6356,
26,
74,
27,
38,
22,
1727,
449,
3707,
9599,
23014,
6418,
20,
5995,
28,
449,
23,
71,
24,
71,
5558,
69,
20,
42,
8642,
6260,
16,
203,
5411,
374,
5841,
7616,
23,
1727,
27,
4577,
72,
20,
73,
9462,
5292,
29,
37,
1077,
24,
4700,
20,
38,
3787,
5340,
69,
2947,
29,
3587,
4700,
9988,
28,
16,
203,
5411,
374,
5841,
5340,
73,
6028,
25,
8285,
6418,
22,
41,
69,
8898,
38,
15237,
20,
40,
21,
71,
40,
74,
39,
20,
7301,
74,
4366,
21,
8955,
4313,
6675,
28,
16,
203,
5411,
374,
17432,
5948,
7140,
24532,
73,
5877,
40,
22,
38,
9462,
2313,
73,
3787,
5482,
2643,
38,
6564,
29003,
41,
24,
12664,
16894,
18212,
16,
203,
5411,
374,
6554,
38,
24,
71,
3361,
72,
42,
7677,
71,
41,
70,
22,
41,
69,
26874,
2
] |
./full_match/1/0xfbc7d0D9885DC4B222e0f488EEf80c493c929D2B/sources/contracts/MyToken.sol | Anti-bot and anti-whale mappings and variables exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract UnibotV2 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 revShareWallet;
address public teamWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public blacklistRenounced = false;
mapping(address => bool) blacklisted;
uint256 public buyTotalFees;
uint256 public buyRevShareFee;
uint256 public buyLiquidityFee;
uint256 public buyTeamFee;
uint256 public sellTotalFees;
uint256 public sellRevShareFee;
uint256 public sellLiquidityFee;
uint256 public sellTeamFee;
uint256 public tokensForRevShare;
uint256 public tokensForLiquidity;
uint256 public tokensForTeam;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
bool public preMigrationPhase = true;
mapping(address => bool) public preMigrationTransferrable;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event revShareWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event teamWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("TwixCoin", "TWIX") {
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 _buyRevShareFee = 2;
uint256 _buyLiquidityFee = 1;
uint256 _buyTeamFee = 2;
uint256 _sellRevShareFee = 2;
uint256 _sellLiquidityFee = 1;
uint256 _sellTeamFee = 2;
uint256 totalSupply = 1_000_000 * 1e18;
buyRevShareFee = _buyRevShareFee;
buyLiquidityFee = _buyLiquidityFee;
buyTeamFee = _buyTeamFee;
buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee;
sellRevShareFee = _sellRevShareFee;
sellLiquidityFee = _sellLiquidityFee;
sellTeamFee = _sellTeamFee;
sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
preMigrationTransferrable[owner()] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
preMigrationPhase = false;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.5%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 10) / 1000) / 1e18,
"Cannot set maxWallet lower than 1.0%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _revShareFee,
uint256 _liquidityFee,
uint256 _teamFee
) external onlyOwner {
buyRevShareFee = _revShareFee;
buyLiquidityFee = _liquidityFee;
buyTeamFee = _teamFee;
buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee;
require(buyTotalFees <= 5, "Buy fees must be <= 5.");
}
function updateSellFees(
uint256 _revShareFee,
uint256 _liquidityFee,
uint256 _teamFee
) external onlyOwner {
sellRevShareFee = _revShareFee;
sellLiquidityFee = _liquidityFee;
sellTeamFee = _teamFee;
sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee;
require(sellTotalFees <= 5, "Sell fees must be <= 5.");
}
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 updateRevShareWallet(address newRevShareWallet) external onlyOwner {
emit revShareWalletUpdated(newRevShareWallet, revShareWallet);
revShareWallet = newRevShareWallet;
}
function updateTeamWallet(address newWallet) external onlyOwner {
emit teamWalletUpdated(newWallet, teamWallet);
teamWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function isBlacklisted(address account) public view returns (bool) {
return blacklisted[account];
}
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");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (
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");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
else if (
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");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
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");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
if (preMigrationPhase) {
require(preMigrationTransferrable[from], "Not authorized to transfer pre-migration.");
}
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."
);
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
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;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForTeam += (fees * sellTeamFee) / sellTotalFees;
tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForTeam += (fees * buyTeamFee) / buyTotalFees;
tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForRevShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForRevShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForRevShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(teamWallet).call{value: ethForTeam}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForRevShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
(success, ) = address(revShareWallet).call{value: address(this).balance}("");
function withdrawStuckUnibot() external onlyOwner {
uint256 balance = IERC20(address(this)).balanceOf(address(this));
IERC20(address(this)).transfer(msg.sender, balance);
payable(msg.sender).transfer(address(this).balance);
}
function withdrawStuckToken(address _token, address _to) external onlyOwner {
require(_token != address(0), "_token address cannot be 0");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(_to, _contractBalance);
}
function withdrawStuckEth(address toAddr) external onlyOwner {
(bool success, ) = toAddr.call{
value: address(this).balance
} ("");
require(success);
}
function withdrawStuckEth(address toAddr) external onlyOwner {
(bool success, ) = toAddr.call{
value: address(this).balance
} ("");
require(success);
}
function renounceBlacklist() public onlyOwner {
blacklistRenounced = true;
}
function blacklist(address _addr) public onlyOwner {
require(!blacklistRenounced, "Team has revoked blacklist rights");
require(
_addr != address(uniswapV2Pair) && _addr != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),
"Cannot blacklist token's v2 router or v2 pool."
);
blacklisted[_addr] = true;
}
function blacklistLiquidityPool(address lpAddress) public onlyOwner {
require(!blacklistRenounced, "Team has revoked blacklist rights");
require(
lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),
"Cannot blacklist token's v2 router or v2 pool."
);
blacklisted[lpAddress] = true;
}
function unblacklist(address _addr) public onlyOwner {
blacklisted[_addr] = false;
}
function setPreMigrationTransferable(address _addr, bool isAuthorized) public onlyOwner {
preMigrationTransferrable[_addr] = isAuthorized;
excludeFromFees(_addr, isAuthorized);
excludeFromMaxTransaction(_addr, isAuthorized);
}
} | 2,908,185 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
4433,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1351,
495,
352,
58,
22,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
5588,
9535,
16936,
31,
203,
565,
1758,
1071,
5927,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
1426,
1071,
11709,
16290,
27373,
273,
629,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
25350,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
10070,
9535,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8689,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
10070,
9535,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
48,
18988,
24237,
14667,
31,
203,
565,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import "./NarwhalRouter.sol";
import "./BMath.sol";
import "./interfaces/IIndexPool.sol";
import "./interfaces/IERC20.sol";
import "./libraries/TransferHelper.sol";
contract IndexedNarwhalRouter is NarwhalRouter, BMath {
using TokenInfo for bytes32;
using TokenInfo for address;
using TransferHelper for address;
using SafeMath for uint256;
constructor(
address _uniswapFactory,
address _sushiswapFactory,
address _weth
) NarwhalRouter(_uniswapFactory, _sushiswapFactory, _weth) {}
/** ========== Mint Single: Exact In ========== */
/**
* @dev Swaps ether for each token in `path` using their Uniswap pairs,
* then mints at least `minPoolAmountOut` pool tokens from `indexPool`.
*
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param indexPool Address of the index pool to mint tokens from.
* @param minPoolAmountOut Amount of pool tokens that must be received to not revert.
*/
function swapExactETHForTokensAndMint(
bytes32[] calldata path,
address indexPool,
uint minPoolAmountOut
) external payable returns (uint poolAmountOut) {
require(path[0].readToken() == address(weth), "NRouter: INVALID_PATH");
uint256[] memory amounts = getAmountsOut(path, msg.value);
weth.deposit{value: amounts[0]}();
address(weth).safeTransfer(pairFor(path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
uint amountOut = amounts[amounts.length - 1];
return _mintExactIn(
path[path.length - 1].readToken(),
amountOut,
indexPool,
minPoolAmountOut
);
}
/**
* @dev Swaps a token for each other token in `path` using their Uniswap pairs,
* then mints at least `minPoolAmountOut` pool tokens from `indexPool`.
*
* @param amountIn Amount of the first token in `path` to swap.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param indexPool Address of the index pool to mint tokens from.
* @param minPoolAmountOut Amount of pool tokens that must be received to not revert.
*/
function swapExactTokensForTokensAndMint(
uint amountIn,
bytes32[] calldata path,
address indexPool,
uint minPoolAmountOut
) external returns (uint poolAmountOut) {
uint256[] memory amounts = getAmountsOut(path, amountIn);
path[0].readToken().safeTransferFrom(
msg.sender, pairFor(path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
uint amountOut = amounts[amounts.length - 1];
return _mintExactIn(
path[path.length - 1].readToken(),
amountOut,
indexPool,
minPoolAmountOut
);
}
function _mintExactIn(
address tokenIn,
uint amountIn,
address indexPool,
uint minPoolAmountOut
) internal returns (uint poolAmountOut) {
TransferHelper.safeApprove(tokenIn, indexPool, amountIn);
poolAmountOut = IIndexPool(indexPool).joinswapExternAmountIn(
tokenIn,
amountIn,
minPoolAmountOut
);
TransferHelper.safeTransfer(indexPool, msg.sender, poolAmountOut);
}
/** ========== Burn Single: Exact In ========== */
/**
* @dev Redeems `poolAmountIn` pool tokens for the first token in `path`
* and swaps it to at least `minAmountOut` of the last token in `path`.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param poolAmountIn Amount of pool tokens to burn.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param minAmountOut Amount of last token in `path` that must be received to not revert.
* @return amountOut Amount of output tokens received.
*/
function burnExactAndSwapForTokens(
address indexPool,
uint poolAmountIn,
bytes32[] calldata path,
uint minAmountOut
) external returns (uint amountOut) {
amountOut = _burnExactAndSwap(
indexPool,
poolAmountIn,
path,
minAmountOut,
msg.sender
);
}
/**
* @dev Redeems `poolAmountIn` pool tokens for the first token in `path`
* and swaps it to at least `minAmountOut` ether.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param poolAmountIn Amount of pool tokens to burn.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param minAmountOut Amount of ether that must be received to not revert.
* @return amountOut Amount of ether received.
*/
function burnExactAndSwapForETH(
address indexPool,
uint poolAmountIn,
bytes32[] calldata path,
uint minAmountOut
) external returns (uint amountOut) {
require(path[path.length - 1].readToken() == address(weth), "NRouter: INVALID_PATH");
amountOut = _burnExactAndSwap(
indexPool,
poolAmountIn,
path,
minAmountOut,
address(this)
);
IWETH(weth).withdraw(amountOut);
TransferHelper.safeTransferETH(msg.sender, amountOut);
}
function _burnExactAndSwap(
address indexPool,
uint poolAmountIn,
bytes32[] memory path,
uint minAmountOut,
address recipient
) internal returns (uint amountOut) {
// Transfer the pool tokens to the router.
TransferHelper.safeTransferFrom(
indexPool,
msg.sender,
address(this),
poolAmountIn
);
// Burn the pool tokens for the first token in `path`.
uint redeemedAmountOut = IIndexPool(indexPool).exitswapPoolAmountIn(
path[0].readToken(),
poolAmountIn,
0
);
// Calculate the swap amounts for the redeemed amount of the first token in `path`.
uint[] memory amounts = getAmountsOut(path, redeemedAmountOut);
amountOut = amounts[amounts.length - 1];
require(amountOut >= minAmountOut, "NRouter: MIN_OUT");
// Transfer the redeemed tokens to the first Uniswap pair.
TransferHelper.safeTransfer(
path[0].readToken(),
pairFor(path[0], path[1]),
amounts[0]
);
// Execute the routed swaps and send the output tokens to `recipient`.
_swap(amounts, path, recipient);
}
/** ========== Mint Single: Exact Out ========== */
/**
* @dev Swaps ether for each token in `path` through Uniswap,
* then mints `poolAmountOut` pool tokens from `indexPool`.
*
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param indexPool Address of the index pool to mint tokens from.
* @param poolAmountOut Amount of pool tokens that must be received to not revert.
*/
function swapETHForTokensAndMintExact(
bytes32[] calldata path,
address indexPool,
uint poolAmountOut
) external payable {
address swapTokenOut = path[path.length - 1].readToken();
uint amountOut = _tokenInGivenPoolOut(indexPool, swapTokenOut, poolAmountOut);
require(path[0].readToken() == address(weth), "INVALID_PATH");
uint[] memory amounts = getAmountsIn(path, amountOut);
require(amounts[0] <= msg.value, "NRouter: MAX_IN");
weth.deposit{value: amounts[0]}();
address(weth).safeTransfer(pairFor(path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
// refund dust eth, if any
if (msg.value > amounts[0]) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
return _mintExactOut(
swapTokenOut,
amountOut,
indexPool,
poolAmountOut
);
}
/**
* @dev Swaps a token for each other token in `path` through Uniswap,
* then mints at least `poolAmountOut` pool tokens from `indexPool`.
*
* @param amountInMax Maximum amount of the first token in `path` to give.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param indexPool Address of the index pool to mint tokens from.
* @param poolAmountOut Amount of pool tokens that must be received to not revert.
*/
function swapTokensForTokensAndMintExact(
uint amountInMax,
bytes32[] calldata path,
address indexPool,
uint poolAmountOut
) external {
address swapTokenOut = path[path.length - 1].readToken();
uint amountOut = _tokenInGivenPoolOut(indexPool, swapTokenOut, poolAmountOut);
uint[] memory amounts = getAmountsIn(path, amountOut);
require(amounts[0] <= amountInMax, "NRouter: MAX_IN");
path[0].readToken().safeTransferFrom(
msg.sender, pairFor(path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
_mintExactOut(
swapTokenOut,
amountOut,
indexPool,
poolAmountOut
);
}
function _mintExactOut(
address tokenIn,
uint amountIn,
address indexPool,
uint poolAmountOut
) internal {
TransferHelper.safeApprove(tokenIn, indexPool, amountIn);
IIndexPool(indexPool).joinswapPoolAmountOut(
tokenIn,
poolAmountOut,
amountIn
);
TransferHelper.safeTransfer(indexPool, msg.sender, poolAmountOut);
}
function _tokenInGivenPoolOut(
address indexPool,
address tokenIn,
uint256 poolAmountOut
) internal view returns (uint256 amountIn) {
IIndexPool.Record memory record = IIndexPool(indexPool).getTokenRecord(tokenIn);
if (!record.ready) {
uint256 minimumBalance = IIndexPool(indexPool).getMinimumBalance(tokenIn);
uint256 realToMinRatio = bdiv(
bsub(minimumBalance, record.balance),
minimumBalance
);
uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio);
record.balance = minimumBalance;
record.denorm = uint96(badd(MIN_WEIGHT, weightPremium));
}
uint256 totalSupply = IERC20(indexPool).totalSupply();
uint256 totalWeight = IIndexPool(indexPool).getTotalDenormalizedWeight();
uint256 swapFee = IIndexPool(indexPool).getSwapFee();
return calcSingleInGivenPoolOut(
record.balance,
record.denorm,
totalSupply,
totalWeight,
poolAmountOut,
swapFee
);
}
/** ========== Burn Single: Exact Out ========== */
/**
* @dev Redeems up to `poolAmountInMax` pool tokens for the first token in `path`
* and swaps it to exactly `tokenAmountOut` of the last token in `path`.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param poolAmountInMax Maximum amount of pool tokens to burn.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param tokenAmountOut Amount of last token in `path` to receive.
* @return poolAmountIn Amount of pool tokens burned.
*/
function burnAndSwapForExactTokens(
address indexPool,
uint poolAmountInMax,
bytes32[] calldata path,
uint tokenAmountOut
) external returns (uint poolAmountIn) {
poolAmountIn = _burnAndSwapForExact(
indexPool,
poolAmountInMax,
path,
tokenAmountOut,
msg.sender
);
}
/**
* @dev Redeems up to `poolAmountInMax` pool tokens for the first token in `path`
* and swaps it to exactly `ethAmountOut` ether.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param poolAmountInMax Maximum amount of pool tokens to burn.
* @param path Array of encoded tokens to swap using the Narwhal router.
* @param ethAmountOut Amount of eth to receive.
* @return poolAmountIn Amount of pool tokens burned.
*/
function burnAndSwapForExactETH(
address indexPool,
uint poolAmountInMax,
bytes32[] calldata path,
uint ethAmountOut
) external returns (uint poolAmountIn) {
require(path[path.length - 1].readToken() == address(weth), "NRouter: INVALID_PATH");
poolAmountIn = _burnAndSwapForExact(
indexPool,
poolAmountInMax,
path,
ethAmountOut,
address(this)
);
IWETH(weth).withdraw(ethAmountOut);
TransferHelper.safeTransferETH(msg.sender, ethAmountOut);
}
function _burnAndSwapForExact(
address indexPool,
uint poolAmountInMax,
bytes32[] memory path,
uint tokenAmountOut,
address recipient
) internal returns (uint poolAmountIn) {
// Transfer the maximum pool tokens to the router.
indexPool.safeTransferFrom(
msg.sender,
address(this),
poolAmountInMax
);
// Calculate the swap amounts for `tokenAmountOut` of the last token in `path`.
uint[] memory amounts = getAmountsIn(path, tokenAmountOut);
// Burn the pool tokens for the exact amount of the first token in `path`.
poolAmountIn = IIndexPool(indexPool).exitswapExternAmountOut(
path[0].readToken(),
amounts[0],
poolAmountInMax
);
// Transfer the redeemed tokens to the first Uniswap pair.
TransferHelper.safeTransfer(
path[0].readToken(),
pairFor(path[0], path[1]),
amounts[0]
);
// Execute the routed swaps and send the output tokens to `recipient`.
_swap(amounts, path, recipient);
// Return any unburned pool tokens to the caller.
indexPool.safeTransfer(
msg.sender,
poolAmountInMax.sub(poolAmountIn)
);
}
/** ========== Mint All: Exact Out ========== */
/**
* @dev Swaps an input token for every underlying token in an index pool,
* then mints `poolAmountOut` pool tokens from the pool.
*
* Up to one intermediary token may be provided in `intermediaries` for each
* underlying token in the index pool.
*
* If a null address is provided as an intermediary, the input token will be
* swapped directly for the output token.
*
* `intermediaries` is an encoded Narwhal path with a one-byte prefix indicating
* whether the first swap should use sushiswap.
*
* @param indexPool Address of the index pool to mint tokens with.
* @param intermediaries Encoded Narwhal tokens array with a one-byte prefix
* indicating whether the swap to the underlying token should use sushiswap.
* @param poolAmountOut Amount of index pool tokens to mint.
* @param tokenIn Token to buy the underlying tokens with.
* @param amountInMax Maximumm amount of `tokenIn` to spend.
* @return Amount of `tokenIn` spent.
*/
function swapTokensForAllTokensAndMintExact(
address indexPool,
bytes32[] calldata intermediaries,
uint256 poolAmountOut,
address tokenIn,
uint256 amountInMax
) external returns (uint256) {
uint256 remainder = amountInMax;
address[] memory tokens = IIndexPool(indexPool).getCurrentTokens();
require(
tokens.length == intermediaries.length,
"NRouter: ARR_LEN"
);
tokenIn.safeTransferFrom(msg.sender, address(this), amountInMax);
uint256[] memory amountsToPool = new uint256[](tokens.length);
uint256 ratio = bdiv(poolAmountOut, IERC20(indexPool).totalSupply());
// Reserve 3 slots in memory for the addresses
bytes32[] memory path = new bytes32[](3);
path[0] = tokenIn.pack(false);
for (uint256 i = 0; i < tokens.length; i++) {
(amountsToPool[i], remainder) = _handleMintInput(
indexPool,
intermediaries[i],
tokens[i],
path,
ratio,
remainder
);
}
IIndexPool(indexPool).joinPool(poolAmountOut, amountsToPool);
TransferHelper.safeTransfer(indexPool, msg.sender, poolAmountOut);
if (remainder > 0) {
tokenIn.safeTransfer(msg.sender, remainder);
}
return amountInMax.sub(remainder);
}
/**
* @dev Swaps ether for every underlying token in an index pool,
* then mints `poolAmountOut` pool tokens from the pool.
*
* Up to one intermediary token may be provided in `intermediaries` for each
* underlying token in the index pool.
*
* If a null address is provided as an intermediary, the input token will be
* swapped directly for the output token.
*
* `intermediaries` is an encoded Narwhal path with a one-byte prefix indicating
* whether the first swap should use sushiswap.
*
* @param indexPool Address of the index pool to mint tokens with.
* @param intermediaries Encoded Narwhal tokens array with a one-byte prefix
* indicating whether the swap to the underlying token should use sushiswap.
* @param poolAmountOut Amount of index pool tokens to mint.
* @return Amount of ether spent.
*/
function swapETHForAllTokensAndMintExact(
address indexPool,
bytes32[] calldata intermediaries,
uint256 poolAmountOut
) external payable returns (uint) {
uint256 remainder = msg.value;
IWETH(weth).deposit{value: msg.value}();
address[] memory tokens = IIndexPool(indexPool).getCurrentTokens();
require(tokens.length == intermediaries.length, "NRouter: ARR_LEN");
uint256[] memory amountsToPool = new uint256[](tokens.length);
uint256 ratio = bdiv(poolAmountOut, IERC20(indexPool).totalSupply());
// Reserve 3 slots in memory for the addresses
bytes32[] memory path = new bytes32[](3);
path[0] = address(weth).pack(false);
for (uint256 i = 0; i < tokens.length; i++) {
(amountsToPool[i], remainder) = _handleMintInput(
indexPool,
intermediaries[i],
tokens[i],
path,
ratio,
remainder
);
}
IIndexPool(indexPool).joinPool(poolAmountOut, amountsToPool);
TransferHelper.safeTransfer(indexPool, msg.sender, poolAmountOut);
if (remainder > 0) {
IWETH(weth).withdraw(remainder);
TransferHelper.safeTransferETH(msg.sender, remainder);
}
return msg.value.sub(remainder);
}
function _handleMintInput(
address indexPool,
bytes32 intermediate,
address poolToken,
bytes32[] memory path,
uint256 poolRatio,
uint256 amountInMax
) internal returns (uint256 amountToPool, uint256 remainder) {
address tokenIn = path[0].readToken();
uint256 usedBalance = IIndexPool(indexPool).getUsedBalance(poolToken);
amountToPool = bmul(poolRatio, usedBalance);
if (tokenIn == poolToken) {
remainder = amountInMax.sub(amountToPool, "NRouter: MAX_IN");
} else {
bool sushiFirst;
assembly {
sushiFirst := shr(168, intermediate)
intermediate := and(
0x0000000000000000000000ffffffffffffffffffffffffffffffffffffffffff,
intermediate
)
}
path[0] = tokenIn.pack(sushiFirst);
if (intermediate == bytes32(0)) {
// If no intermediate token is given, set path length to 2 so the other
// functions will not use the 3rd address.
assembly { mstore(path, 2) }
// It doesn't matter whether a token is set to use sushi or not
// if it is the last token in the list.
path[1] = poolToken.pack(false);
} else {
// If an intermediary is given, set path length to 3 so the other
// functions will use all addresses.
assembly { mstore(path, 3) }
path[1] = intermediate;
path[2] = poolToken.pack(false);
}
uint[] memory amounts = getAmountsIn(path, amountToPool);
remainder = amountInMax.sub(amounts[0], "NRouter: MAX_IN");
tokenIn.safeTransfer(pairFor(path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
}
poolToken.safeApprove(indexPool, amountToPool);
}
/** ========== Burn All: Exact In ========== */
/**
* @dev Burns `poolAmountOut` for all the underlying tokens in a pool, then
* swaps each of them on Uniswap for at least `minAmountOut` of `tokenOut`.
*
* Up to one intermediary token may be provided in `intermediaries` for each
* underlying token in the index pool.
*
* If a null address is provided as an intermediary, the input token will be
* swapped directly for the output token.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param minAmountsOut Minimum amount of each underlying token that must be
* received from the pool to not revert.
* @param intermediaries Encoded Narwhal tokens array with a one-byte prefix
* indicating whether the swap to the underlying token should use sushiswap.
* @param poolAmountIn Amount of index pool tokens to burn.
* @param tokenOut Address of the token to buy.
* @param minAmountOut Minimum amount of `tokenOut` that must be received to
* not revert.
* @return amountOutTotal Amount of `tokenOut` received.
*/
function burnForAllTokensAndSwapForTokens(
address indexPool,
uint256[] calldata minAmountsOut,
bytes32[] calldata intermediaries,
uint256 poolAmountIn,
address tokenOut,
uint256 minAmountOut
) external returns (uint256 amountOutTotal) {
amountOutTotal = _burnForAllTokensAndSwap(
indexPool,
tokenOut,
minAmountsOut,
intermediaries,
poolAmountIn,
minAmountOut,
msg.sender
);
}
/**
* @dev Burns `poolAmountOut` for all the underlying tokens in a pool, then
* swaps each of them on Uniswap for at least `minAmountOut` ether.
*
* Up to one intermediary token may be provided in `intermediaries` for each
* underlying token in the index pool.
*
* If a null address is provided as an intermediary, the input token will be
* swapped directly for the output token.
*
* @param indexPool Address of the index pool to burn tokens from.
* @param minAmountsOut Minimum amount of each underlying token that must be
* received from the pool to not revert.
* @param intermediaries Encoded Narwhal tokens array with a one-byte prefix
* indicating whether the swap to the underlying token should use sushiswap.
* @param poolAmountIn Amount of index pool tokens to burn.
* @param minAmountOut Minimum amount of ether that must be received to
* not revert.
* @return amountOutTotal Amount of ether received.
*/
function burnForAllTokensAndSwapForETH(
address indexPool,
uint256[] calldata minAmountsOut,
bytes32[] calldata intermediaries,
uint256 poolAmountIn,
uint256 minAmountOut
) external returns (uint amountOutTotal) {
amountOutTotal = _burnForAllTokensAndSwap(
indexPool,
address(weth),
minAmountsOut,
intermediaries,
poolAmountIn,
minAmountOut,
address(this)
);
IWETH(weth).withdraw(amountOutTotal);
TransferHelper.safeTransferETH(msg.sender, amountOutTotal);
}
function _burnForAllTokensAndSwap(
address indexPool,
address tokenOut,
uint256[] calldata minAmountsOut,
bytes32[] calldata intermediaries,
uint256 poolAmountIn,
uint256 minAmountOut,
address recipient
) internal returns (uint amountOutTotal) {
// Transfer the pool tokens from the caller.
TransferHelper.safeTransferFrom(indexPool, msg.sender, address(this), poolAmountIn);
address[] memory tokens = IIndexPool(indexPool).getCurrentTokens();
require(
intermediaries.length == tokens.length && minAmountsOut.length == tokens.length,
"IndexedUniswapRouterBurner: BAD_ARRAY_LENGTH"
);
IIndexPool(indexPool).exitPool(poolAmountIn, minAmountsOut);
// Reserve 3 slots in memory for the addresses
bytes32[] memory path = new bytes32[](3);
for (uint256 i = 0; i < tokens.length; i++) {
uint amountOut = _handleBurnOutput(
tokens[i],
intermediaries[i],
tokenOut,
path,
recipient
);
amountOutTotal = amountOutTotal.add(amountOut);
}
require(amountOutTotal >= minAmountOut, "NRouter: MIN_OUT");
}
function _handleBurnOutput(
address tokenIn,
bytes32 intermediate,
address tokenOut,
bytes32[] memory path,
address recipient
) internal returns (uint amountOut) {
uint256 _balance = IERC20(tokenIn).balanceOf(address(this));
if (tokenIn == tokenOut) {
amountOut = _balance;
if (recipient != address(this)) {
tokenIn.safeTransfer(recipient, _balance);
}
} else {
bool sushiFirst;
assembly {
sushiFirst := shr(168, intermediate)
intermediate := and(
0x0000000000000000000000ffffffffffffffffffffffffffffffffffffffffff,
intermediate
)
}
path[0] = tokenIn.pack(sushiFirst);
if (intermediate == bytes32(0)) {
// If no intermediate token is given, set path length to 2 so the other
// functions will not use the 3rd address.
assembly { mstore(path, 2) }
// It doesn't matter whether a token is set to use sushi or not
// if it is the last token in the list.
path[1] = tokenOut.pack(false);
} else {
// If an intermediary is given, set path length to 3 so the other
// functions will use all addresses.
assembly { mstore(path, 3) }
path[1] = intermediate;
path[2] = tokenOut.pack(false);
}
uint[] memory amounts = getAmountsOut(path, _balance);
tokenIn.safeTransfer(pairFor(path[0], path[1]), amounts[0]);
_swap(amounts, path, recipient);
amountOut = amounts[amounts.length - 1];
}
}
} | Transfer the pool tokens from the caller. Reserve 3 slots in memory for the addresses | function _burnForAllTokensAndSwap(
address indexPool,
address tokenOut,
uint256[] calldata minAmountsOut,
bytes32[] calldata intermediaries,
uint256 poolAmountIn,
uint256 minAmountOut,
address recipient
) internal returns (uint amountOutTotal) {
TransferHelper.safeTransferFrom(indexPool, msg.sender, address(this), poolAmountIn);
address[] memory tokens = IIndexPool(indexPool).getCurrentTokens();
require(
intermediaries.length == tokens.length && minAmountsOut.length == tokens.length,
"IndexedUniswapRouterBurner: BAD_ARRAY_LENGTH"
);
IIndexPool(indexPool).exitPool(poolAmountIn, minAmountsOut);
bytes32[] memory path = new bytes32[](3);
for (uint256 i = 0; i < tokens.length; i++) {
uint amountOut = _handleBurnOutput(
tokens[i],
intermediaries[i],
tokenOut,
path,
recipient
);
amountOutTotal = amountOutTotal.add(amountOut);
}
require(amountOutTotal >= minAmountOut, "NRouter: MIN_OUT");
}
| 12,944,767 | [
1,
5912,
326,
2845,
2430,
628,
326,
4894,
18,
1124,
6527,
890,
12169,
316,
3778,
364,
326,
6138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
70,
321,
1290,
1595,
5157,
1876,
12521,
12,
203,
565,
1758,
770,
2864,
16,
203,
565,
1758,
1147,
1182,
16,
203,
565,
2254,
5034,
8526,
745,
892,
1131,
6275,
87,
1182,
16,
203,
565,
1731,
1578,
8526,
745,
892,
1554,
5660,
5646,
16,
203,
565,
2254,
5034,
2845,
6275,
382,
16,
203,
565,
2254,
5034,
1131,
6275,
1182,
16,
203,
565,
1758,
8027,
203,
225,
262,
2713,
1135,
261,
11890,
3844,
1182,
5269,
13,
288,
203,
565,
12279,
2276,
18,
4626,
5912,
1265,
12,
1615,
2864,
16,
1234,
18,
15330,
16,
1758,
12,
2211,
3631,
2845,
6275,
382,
1769,
203,
565,
1758,
8526,
3778,
2430,
273,
467,
1016,
2864,
12,
1615,
2864,
2934,
588,
3935,
5157,
5621,
203,
565,
2583,
12,
203,
1377,
1554,
5660,
5646,
18,
2469,
422,
2430,
18,
2469,
597,
1131,
6275,
87,
1182,
18,
2469,
422,
2430,
18,
2469,
16,
203,
1377,
315,
15034,
984,
291,
91,
438,
8259,
38,
321,
264,
30,
16467,
67,
8552,
67,
7096,
6,
203,
565,
11272,
203,
565,
467,
1016,
2864,
12,
1615,
2864,
2934,
8593,
2864,
12,
6011,
6275,
382,
16,
1131,
6275,
87,
1182,
1769,
203,
565,
1731,
1578,
8526,
3778,
589,
273,
394,
1731,
1578,
8526,
12,
23,
1769,
203,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2430,
18,
2469,
31,
277,
27245,
288,
203,
1377,
2254,
3844,
1182,
273,
389,
4110,
38,
321,
1447,
12,
203,
3639,
2430,
63,
77,
6487,
203,
3639,
1554,
5660,
5646,
63,
77,
6487,
203,
3639,
1147,
2
] |
pragma solidity ^0.4.19;
/**
* BRX.SPACE ([email protected])
*
* BRX token is a virtual token, governed by ERC20-compatible
* Ethereum Smart Contract and secured by Ethereum Blockchain
*
* The official website is https://brx.space
*
* The uints are all in wei and atto tokens (*10^-18)
* The contract code itself, as usual, is at the end, after all the connected libraries
* Developed by 262dfb6c55bf6ac215fac30181bdbfb8a2872cc7e3ea7cffe3a001621bb559e2
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min256(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* Fix for the ERC20 short address attack
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool) {
require(_to != address(0) &&
_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_to != address(0) &&
_value <= balances[_from] &&
_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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BRXToken is StandardToken, Ownable {
using SafeMath for uint;
//--------------- Info for ERC20 explorers -----------------//
string public constant name = "BRX Coin";
string public constant symbol = "BRX";
uint8 public constant decimals = 18;
//---------------------- Constants -------------------------//
uint private constant atto = 1000000000000000000;
uint private constant INITIAL_SUPPLY = 15000000 * atto; // 15 mln BRX. Impossible to mint more than this
uint public totalSupply = INITIAL_SUPPLY;
//---------------------- Variables -------------------------//
// Made up ICO address (designating the token pool reserved for ICO, no one has access to it)
address public ico_address = 0x1F01f01f01f01F01F01f01F01F01f01F01f01F01;
address public teamWallet = 0x58096c1dCd5f338530770B1f6Fe0AcdfB90Cc87B;
address public addrBRXPay = 0x2F02F02F02F02f02f02f02f02F02F02f02f02f02;
uint private current_supply = 0; // Holding the number of all the coins in existence
uint private ico_starting_supply = 0; // How many atto tokens *were* available for sale at the beginning of the ICO
uint private current_price_atto_tokens_per_wei = 0; // Holding current price (determined by the algorithm in buy())
//-------------- Flags describing ICO stages ---------------//
bool private preSoldSharesDistributed = false; // Prevents accidental re-distribution of shares
bool private isICOOpened = false;
bool private isICOClosed = false;
// 3 stages:
// Contract has just been deployed and initialized. isICOOpened == false, isICOClosed == false
// ICO has started, now anybody can buy(). isICOOpened == true, isICOClosed == false
// ICO has finished, now the team can receive the ether. isICOOpened == false, isICOClosed == true
//------------------- Founder Members ----------------------//
uint public founderMembers = 0;
mapping(uint => address) private founderOwner;
mapping(address => uint) founderMembersInvest;
//---------------------- Premiums --------------------------//
uint[] private premiumPacks;
mapping(address => bool) private premiumICOMember;
mapping(address => uint) private premiumPacksPaid;
mapping(address => bool) public frozenAccounts;
//----------------------- Events ---------------------------//
event ICOOpened();
event ICOClosed();
event PriceChanged(uint old_price, uint new_price);
event SupplyChanged(uint supply, uint old_supply);
event FrozenFund(address _from, bool _freeze);
event BRXAcquired(address account, uint amount_in_wei, uint amount_in_brx);
event BRXNewFounder(address account, uint amount_in_brx);
// ***************************************************************************
// Constructor
function BRXToken() public {
// Some percentage of the tokens is already reserved by early employees and investors
// Here we're initializing their balances
distributePreSoldShares();
// Starting price
current_price_atto_tokens_per_wei = calculateCurrentPrice(1);
// Some other initializations
premiumPacks.length = 0;
}
// Sending ether directly to the contract invokes buy() and assigns tokens to the sender
function () public payable {
buy();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(
address tokenAddress, uint tokens
) public onlyOwner
returns (bool success) {
return StandardToken(tokenAddress).transfer(owner, tokens);
}
// ***************************************************************************
// Buy token by sending ether here
//
// Price is being determined by the algorithm in recalculatePrice()
// You can also send the ether directly to the contract address
function buy() public payable {
require(msg.value != 0 && isICOOpened == true && isICOClosed == false);
// Deciding how many tokens can be bought with the ether received
uint tokens = getAttoTokensAmountPerWeiInternal(msg.value);
// Don't allow to buy more than 1% per transaction (secures from huge investors swalling the whole thing in 1 second)
uint allowedInOneTransaction = current_supply / 100;
require(tokens < allowedInOneTransaction &&
tokens <= balances[ico_address]);
// Transfer from the ICO pool
balances[ico_address] = balances[ico_address].sub(tokens); // if not enough, will throw
balances[msg.sender] = balances[msg.sender].add(tokens);
premiumICOMember[msg.sender] = true;
// Check if sender has become a founder member
if (balances[msg.sender] >= 2000000000000000000000) {
if (founderMembersInvest[msg.sender] == 0) {
founderOwner[founderMembers] = msg.sender;
founderMembers++; BRXNewFounder(msg.sender, balances[msg.sender]);
}
founderMembersInvest[msg.sender] = balances[msg.sender];
}
// Kick the price changing algo
uint old_price = current_price_atto_tokens_per_wei;
current_price_atto_tokens_per_wei = calculateCurrentPrice(getAttoTokensBoughtInICO());
if (current_price_atto_tokens_per_wei == 0) current_price_atto_tokens_per_wei = 1; // in case it is too small that it gets rounded to zero
if (current_price_atto_tokens_per_wei > old_price) current_price_atto_tokens_per_wei = old_price; // in case some weird overflow happens
// Broadcasting price change event
if (old_price != current_price_atto_tokens_per_wei) PriceChanged(old_price, current_price_atto_tokens_per_wei);
// Broadcasting the buying event
BRXAcquired(msg.sender, msg.value, tokens);
}
// Formula for the dynamic price change algorithm
function calculateCurrentPrice(
uint attoTokensBought
) private pure
returns (uint result) {
// see http://www.wolframalpha.com/input/?i=f(x)+%3D+395500000+%2F+(x+%2B+150000)+-+136
// mixing safe and usual math here because the division will throw on inconsistency
return (395500000 / ((attoTokensBought / atto) + 150000)).sub(136);
}
// ***************************************************************************
// Functions for the contract owner
function openICO() public onlyOwner {
require(isICOOpened == false && isICOClosed == false);
isICOOpened = true;
ICOOpened();
}
function closeICO() public onlyOwner {
require(isICOClosed == false && isICOOpened == true);
isICOOpened = false;
isICOClosed = true;
// Redistribute ICO Tokens that were not bought as the first premiums
premiumPacks.length = 1;
premiumPacks[0] = balances[ico_address];
balances[ico_address] = 0;
ICOClosed();
}
function pullEtherFromContract() public onlyOwner {
require(isICOClosed == true); // Only when ICO is closed
if (!teamWallet.send(this.balance)) {
revert();
}
}
function freezeAccount(
address _from, bool _freeze
) public onlyOwner
returns (bool) {
frozenAccounts[_from] = _freeze;
FrozenFund(_from, _freeze);
return true;
}
function setNewBRXPay(
address newBRXPay
) public onlyOwner {
require(newBRXPay != address(0));
addrBRXPay = newBRXPay;
}
function transferFromBRXPay(
address _from, address _to, uint _value
) public allowedPayments
returns (bool) {
require(msg.sender == addrBRXPay && balances[_to].add(_value) > balances[_to] &&
_value <= balances[_from] && !frozenAccounts[_from] &&
!frozenAccounts[_to] && _to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function setCurrentPricePerWei(
uint _new_price
) public onlyOwner
returns (bool) {
require(isICOClosed == true && _new_price > 0); // Only when ICO is closed
uint old_price = current_price_atto_tokens_per_wei;
current_price_atto_tokens_per_wei = _new_price;
PriceChanged(old_price, current_price_atto_tokens_per_wei);
}
// ***************************************************************************
// Some percentage of the tokens is already reserved by early employees and investors
// Here we're initializing their balances
function distributePreSoldShares() private onlyOwner {
// Making it impossible to call this function twice
require(preSoldSharesDistributed == false);
preSoldSharesDistributed = true;
// Values are in atto tokens
balances[0xAEC5cbcCF89fc25e955A53A5a015f7702a14b629] = 7208811 * atto;
balances[0xAECDCB2a8e2cFB91869A9af30050BEa038034949] = 4025712 * atto;
balances[0xAECF0B1b6897195295FeeD1146F3732918a5b3E4] = 300275 * atto;
balances[0xAEC80F0aC04f389E84F3f4b39827087e393EB229] = 150000 * atto;
balances[0xAECc9545385d858D3142023d3c298a1662Aa45da] = 150000 * atto;
balances[0xAECE71616d07F609bd2CbD4122FbC9C4a2D11A9D] = 90000 * atto;
balances[0xAECee3E9686825e0c8ea65f1bC8b1aB613545B8e] = 75000 * atto;
balances[0xAECC8E8908cE17Dd6dCFFFDCCD561696f396148F] = 202 * atto;
current_supply = (7208811 + 4025712 + 300275 + 150000 + 150000 + 90000 + 75000 + 202) * atto;
// Sending the rest to ICO pool
balances[ico_address] = INITIAL_SUPPLY.sub(current_supply);
// Initializing the supply variables
ico_starting_supply = balances[ico_address];
current_supply = INITIAL_SUPPLY;
SupplyChanged(0, current_supply);
}
// ***************************************************************************
// Some useful getters (although you can just query the public variables)
function getIcoStatus() public view
returns (string result) {
return (isICOClosed) ? 'closed' : (isICOOpened) ? 'opened' : 'not opened' ;
}
function getCurrentPricePerWei() public view
returns (uint result) {
return current_price_atto_tokens_per_wei;
}
function getAttoTokensAmountPerWeiInternal(
uint value
) public payable
returns (uint result) {
return value * current_price_atto_tokens_per_wei;
}
function getAttoTokensAmountPerWei(
uint value
) public view
returns (uint result) {
return value * current_price_atto_tokens_per_wei;
}
function getAttoTokensLeftForICO() public view
returns (uint result) {
return balances[ico_address];
}
function getAttoTokensBoughtInICO() public view
returns (uint result) {
return ico_starting_supply - getAttoTokensLeftForICO();
}
function getPremiumPack(uint index) public view
returns (uint premium) {
return premiumPacks[index];
}
function getPremiumsAvailable() public view
returns (uint length) {
return premiumPacks.length;
}
function getBalancePremiumsPaid(
address account
) public view
returns (uint result) {
return premiumPacksPaid[account];
}
function getAttoTokensToBeFounder() public view
returns (uint result) {
return 2000000000000000000000 / getCurrentPricePerWei();
}
function getFounderMembersInvest(
address account
) public view
returns (uint result) {
return founderMembersInvest[account];
}
function getFounderMember(
uint index
) public onlyOwner view
returns (address account) {
require(founderMembers >= index && founderOwner[index] != address(0));
return founderOwner[index];
}
// ***************************************************************************
// Premiums
function sendPremiumPack(
uint amount
) public onlyOwner allowedPayments {
premiumPacks.length += 1;
premiumPacks[premiumPacks.length-1] = amount;
balances[msg.sender] = balances[msg.sender].sub(amount); // will throw and revert the whole thing if doesn't have this amount
}
function getPremiums() public allowedPayments
returns (uint amount) {
require(premiumICOMember[msg.sender]);
if (premiumPacks.length > premiumPacksPaid[msg.sender]) {
uint startPackIndex = premiumPacksPaid[msg.sender];
uint finishPackIndex = premiumPacks.length - 1;
uint owingTotal = 0;
for(uint i = startPackIndex; i <= finishPackIndex; i++) {
if (current_supply != 0) { // just in case
uint owing = balances[msg.sender] * premiumPacks[i] / current_supply;
balances[msg.sender] = balances[msg.sender].add(owing);
owingTotal = owingTotal + owing;
}
}
premiumPacksPaid[msg.sender] = premiumPacks.length;
return owingTotal;
} else {
revert();
}
}
// ***************************************************************************
// Overriding payment functions to take control over the logic
modifier allowedPayments() {
// Don't allow to transfer coins until the ICO ends
require(isICOOpened == false && isICOClosed == true && !frozenAccounts[msg.sender]);
_;
}
function transferFrom(
address _from, address _to, uint _value
) public allowedPayments
returns (bool) {
super.transferFrom(_from, _to, _value);
}
function transfer(
address _to, uint _value
) public onlyPayloadSize(2 * 32) allowedPayments
returns (bool) {
super.transfer(_to, _value);
}
} | * @title Standard ERC20 token @dev Implementation of the basic standard token./ | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint)) internal allowed;
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_to != address(0) &&
_value <= balances[_from] &&
_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);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} else {
}
| 6,416,559 | [
1,
8336,
4232,
39,
3462,
1147,
225,
25379,
434,
326,
5337,
4529,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8263,
1345,
353,
4232,
39,
3462,
16,
7651,
1345,
288,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
3719,
2713,
2935,
31,
203,
203,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
13,
597,
203,
3639,
389,
1132,
1648,
324,
26488,
63,
67,
2080,
65,
597,
203,
3639,
389,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
203,
565,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
565,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
2
] |
//Address: 0x9dd4f632ff76766f4c238741d2f093a3323c4fc5
//Contract name: B2BKToken
//Balance: 0 Ether
//Verification Date: 10/26/2017
//Transacion Count: 19
// CODE STARTS HERE
pragma solidity ^0.4.16;
/// @title SafeMath
/// @dev Math operations with safety checks that throw on error
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract IOwned {
function owner() public constant returns (address) { owner; }
}
contract Owned is IOwned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
}
/// @title B2BK (B2BX) contract interface
contract IB2BKToken {
function totalSupply() public constant returns (uint256) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function transfer(address _to, uint256 _value) public returns (bool success);
event Buy(address indexed _from, address indexed _to, uint256 _rate, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event FundTransfer(address indexed backer, uint amount, bool isContribution);
event UpdateRate(uint256 _rate);
event Finalize(address indexed _from, uint256 _value);
event Burn(address indexed _from, uint256 _value);
}
/// @title B2BK (B2BX) contract - integration code for KICKICO.
contract B2BKToken is IB2BKToken, Owned {
using SafeMath for uint256;
string public constant name = "B2BX KICKICO";
string public constant symbol = "B2BK";
uint8 public constant decimals = 18;
uint256 public totalSupply = 0;
// Total number of tokens available for BUY.
uint256 public constant totalMaxBuy = 5000000 ether;
// The total number of ETH.
uint256 public totalETH = 0;
address public wallet;
uint256 public rate = 0;
// The flag indicates is in transfers state.
bool public transfers = false;
// The flag indicates is in BUY state.
bool public finalized = false;
mapping (address => uint256) public balanceOf;
/// @notice B2BK Project - Initializing.
/// @dev Constructor.
function B2BKToken(address _wallet, uint256 _rate) validAddress(_wallet) {
wallet = _wallet;
rate = _rate;
}
modifier validAddress(address _address) {
assert(_address != 0x0);
_;
}
modifier transfersAllowed {
require(transfers);
_;
}
modifier isFinalized {
require(finalized);
_;
}
modifier isNotFinalized {
require(!finalized);
_;
}
/// @notice This function is disabled. Addresses having B2BK tokens automatically receive an equal number of B2BX tokens.
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
return false;
}
/// @notice This function if anybody sends ETH directly to this contract, consider he is getting B2BK.
function () payable {
buy(msg.sender);
}
/// @notice This function sends B2BK tokens to the specified address when sending ETH
/// @param _to Address of the recipient
function buy(address _to) public validAddress(_to) isNotFinalized payable {
uint256 _amount = msg.value;
assert(_amount > 0);
uint256 _tokens = _amount.mul(rate);
assert(totalSupply.add(_tokens) <= totalMaxBuy);
totalSupply = totalSupply.add(_tokens);
totalETH = totalETH.add(_amount);
balanceOf[_to] = balanceOf[_to].add(_tokens);
wallet.transfer(_amount);
Buy(msg.sender, _to, rate, _tokens);
Transfer(this, _to, _tokens);
FundTransfer(msg.sender, _amount, true);
}
/// @notice This function updates rates.
function updateRate(uint256 _rate) external isNotFinalized onlyOwner {
rate = _rate;
UpdateRate(rate);
}
/// @notice This function completes BUY tokens.
function finalize() external isNotFinalized onlyOwner {
finalized = true;
Finalize(msg.sender, totalSupply);
}
/// @notice This function burns all B2BK tokens on the address that caused this function.
function burn() external isFinalized {
uint256 _balance = balanceOf[msg.sender];
assert(_balance > 0);
totalSupply = totalSupply.sub(_balance);
balanceOf[msg.sender] = 0;
Burn(msg.sender, _balance);
}
}
| @notice This function burns all B2BK tokens on the address that caused this function. | function burn() external isFinalized {
uint256 _balance = balanceOf[msg.sender];
assert(_balance > 0);
totalSupply = totalSupply.sub(_balance);
balanceOf[msg.sender] = 0;
Burn(msg.sender, _balance);
}
| 1,075,155 | [
1,
2503,
445,
18305,
87,
777,
605,
22,
38,
47,
2430,
603,
326,
1758,
716,
15848,
333,
445,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
1435,
3903,
29200,
1235,
288,
203,
3639,
2254,
5034,
389,
12296,
273,
11013,
951,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
1815,
24899,
12296,
405,
374,
1769,
203,
203,
3639,
2078,
3088,
1283,
273,
2078,
3088,
1283,
18,
1717,
24899,
12296,
1769,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
374,
31,
203,
203,
3639,
605,
321,
12,
3576,
18,
15330,
16,
389,
12296,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.4 <0.7.0;
pragma experimental ABIEncoderV2;
contract view_pure_payable {
//Modificador de view
string[] lista_alumnos;
function nuevo_alumno(string memory _alumno) public {
lista_alumnos.push(_alumno);
}
function ver_alumno(uint _posicion) public view returns(string memory) {
return lista_alumnos[_posicion];
}
uint x=10;
function sumarAx(uint _a) public view returns(uint) {
return x + _a;
}
//Modificador de pure
function exponenciacion(uint _a, uint _b) public pure returns(uint) {
return _a**_b;
}
//Modificador de payable
mapping(address => cartera) DineroCartera;
struct cartera{
string nombre_persona;
address direccion_persona;
uint dinero_persona;
}
function Pagar(string memory _nombrePersona, uint _cantidad) public payable {
cartera memory mi_cartera;
mi_cartera = cartera(_nombrePersona, msg.sender, _cantidad);
DineroCartera[msg.sender] = mi_cartera;
}
function verSaldo() public view returns(cartera memory) {
return DineroCartera[msg.sender];
}
} | Modificador de payable | mapping(address => cartera) DineroCartera;
| 12,869,901 | [
1,
1739,
1507,
23671,
443,
8843,
429,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
5926,
387,
69,
13,
463,
267,
2439,
39,
14153,
69,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0 <0.9.0;
/// @notice Based on https://github.com/madler/zlib/blob/master/contrib/puff
library InflateLib {
// Maximum bits in a code
uint256 constant MAXBITS = 15;
// Maximum number of literal/length codes
uint256 constant MAXLCODES = 286;
// Maximum number of distance codes
uint256 constant MAXDCODES = 30;
// Maximum codes lengths to read
uint256 constant MAXCODES = (MAXLCODES + MAXDCODES);
// Number of fixed literal/length codes
uint256 constant FIXLCODES = 288;
// Error codes
enum ErrorCode {
ERR_NONE, // 0 successful inflate
ERR_NOT_TERMINATED, // 1 available inflate data did not terminate
ERR_OUTPUT_EXHAUSTED, // 2 output space exhausted before completing inflate
ERR_INVALID_BLOCK_TYPE, // 3 invalid block type (type == 3)
ERR_STORED_LENGTH_NO_MATCH, // 4 stored block length did not match one's complement
ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES, // 5 dynamic block code description: too many length or distance codes
ERR_CODE_LENGTHS_CODES_INCOMPLETE, // 6 dynamic block code description: code lengths codes incomplete
ERR_REPEAT_NO_FIRST_LENGTH, // 7 dynamic block code description: repeat lengths with no first length
ERR_REPEAT_MORE, // 8 dynamic block code description: repeat more than specified lengths
ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS, // 9 dynamic block code description: invalid literal/length code lengths
ERR_INVALID_DISTANCE_CODE_LENGTHS, // 10 dynamic block code description: invalid distance code lengths
ERR_MISSING_END_OF_BLOCK, // 11 dynamic block code description: missing end-of-block code
ERR_INVALID_LENGTH_OR_DISTANCE_CODE, // 12 invalid literal/length or distance code in fixed or dynamic block
ERR_DISTANCE_TOO_FAR, // 13 distance is too far back in fixed or dynamic block
ERR_CONSTRUCT // 14 internal: error in construct()
}
// Input and output state
struct State {
//////////////////
// Output state //
//////////////////
// Output buffer
bytes output;
// Bytes written to out so far
uint256 outcnt;
/////////////////
// Input state //
/////////////////
// Input buffer
bytes input;
// Bytes read so far
uint256 incnt;
////////////////
// Temp state //
////////////////
// Bit buffer
uint256 bitbuf;
// Number of bits in bit buffer
uint256 bitcnt;
//////////////////////////
// Static Huffman codes //
//////////////////////////
Huffman lencode;
Huffman distcode;
}
// Huffman code decoding tables
struct Huffman {
uint256[] counts;
uint256[] symbols;
}
function bits(State memory s, uint256 need)
private
pure
returns (ErrorCode, uint256)
{
// Bit accumulator (can use up to 20 bits)
uint256 val;
// Load at least need bits into val
val = s.bitbuf;
while (s.bitcnt < need) {
if (s.incnt == s.input.length) {
// Out of input
return (ErrorCode.ERR_NOT_TERMINATED, 0);
}
// Load eight bits
val |= uint256(uint8(s.input[s.incnt++])) << s.bitcnt;
s.bitcnt += 8;
}
// Drop need bits and update buffer, always zero to seven bits left
s.bitbuf = val >> need;
s.bitcnt -= need;
// Return need bits, zeroing the bits above that
uint256 ret = (val & ((1 << need) - 1));
return (ErrorCode.ERR_NONE, ret);
}
function _stored(State memory s) private pure returns (ErrorCode) {
// Length of stored block
uint256 len;
// Discard leftover bits from current byte (assumes s.bitcnt < 8)
s.bitbuf = 0;
s.bitcnt = 0;
// Get length and check against its one's complement
if (s.incnt + 4 > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
len = uint256(uint8(s.input[s.incnt++]));
len |= uint256(uint8(s.input[s.incnt++])) << 8;
if (
uint8(s.input[s.incnt++]) != (~len & 0xFF) ||
uint8(s.input[s.incnt++]) != ((~len >> 8) & 0xFF)
) {
// Didn't match complement!
return ErrorCode.ERR_STORED_LENGTH_NO_MATCH;
}
// Copy len bytes from in to out
if (s.incnt + len > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
if (s.outcnt + len > s.output.length) {
// Not enough output space
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt++] = s.input[s.incnt++];
}
// Done with a valid stored block
return ErrorCode.ERR_NONE;
}
function _decode(State memory s, Huffman memory h)
private
pure
returns (ErrorCode, uint256)
{
// Current number of bits in code
uint256 len;
// Len bits being decoded
uint256 code = 0;
// First code of length len
uint256 first = 0;
// Number of codes of length len
uint256 count;
// Index of first code of length len in symbol table
uint256 index = 0;
// Error code
ErrorCode err;
for (len = 1; len <= MAXBITS; len++) {
// Get next bit
uint256 tempCode;
(err, tempCode) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, 0);
}
code |= tempCode;
count = h.counts[len];
// If length len, return symbol
if (code < first + count) {
return (ErrorCode.ERR_NONE, h.symbols[index + (code - first)]);
}
// Else update for next length
index += count;
first += count;
first <<= 1;
code <<= 1;
}
// Ran out of codes
return (ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE, 0);
}
function _construct(
Huffman memory h,
uint256[] memory lengths,
uint256 n,
uint256 start
) private pure returns (ErrorCode) {
// Current symbol when stepping through lengths[]
uint256 symbol;
// Current length when stepping through h.counts[]
uint256 len;
// Number of possible codes left of current length
uint256 left;
// Offsets in symbol table for each length
uint256[MAXBITS + 1] memory offs;
// Count number of codes of each length
for (len = 0; len <= MAXBITS; len++) {
h.counts[len] = 0;
}
for (symbol = 0; symbol < n; symbol++) {
// Assumes lengths are within bounds
h.counts[lengths[start + symbol]]++;
}
// No codes!
if (h.counts[0] == n) {
// Complete, but decode() will fail
return (ErrorCode.ERR_NONE);
}
// Check for an over-subscribed or incomplete set of lengths
// One possible code of zero length
left = 1;
for (len = 1; len <= MAXBITS; len++) {
// One more bit, double codes left
left <<= 1;
if (left < h.counts[len]) {
// Over-subscribed--return error
return ErrorCode.ERR_CONSTRUCT;
}
// Deduct count from possible codes
left -= h.counts[len];
}
// Generate offsets into symbol table for each length for sorting
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + h.counts[len];
}
// Put symbols in table sorted by length, by symbol order within each length
for (symbol = 0; symbol < n; symbol++) {
if (lengths[start + symbol] != 0) {
h.symbols[offs[lengths[start + symbol]]++] = symbol;
}
}
// Left > 0 means incomplete
return left > 0 ? ErrorCode.ERR_CONSTRUCT : ErrorCode.ERR_NONE;
}
function _codes(
State memory s,
Huffman memory lencode,
Huffman memory distcode
) private pure returns (ErrorCode) {
// Decoded symbol
uint256 symbol;
// Length for copy
uint256 len;
// Distance for copy
uint256 dist;
// TODO Solidity doesn't support constant arrays, but these are fixed at compile-time
// Size base for length codes 257..285
uint16[29] memory lens =
[
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
15,
17,
19,
23,
27,
31,
35,
43,
51,
59,
67,
83,
99,
115,
131,
163,
195,
227,
258
];
// Extra bits for length codes 257..285
uint8[29] memory lext =
[
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
0
];
// Offset base for distance codes 0..29
uint16[30] memory dists =
[
1,
2,
3,
4,
5,
7,
9,
13,
17,
25,
33,
49,
65,
97,
129,
193,
257,
385,
513,
769,
1025,
1537,
2049,
3073,
4097,
6145,
8193,
12289,
16385,
24577
];
// Extra bits for distance codes 0..29
uint8[30] memory dext =
[
0,
0,
0,
0,
1,
1,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
7,
8,
8,
9,
9,
10,
10,
11,
11,
12,
12,
13,
13
];
// Error code
ErrorCode err;
// Decode literals and length/distance pairs
while (symbol != 256) {
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
if (symbol < 256) {
// Literal: symbol is the byte
// Write out the literal
if (s.outcnt == s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
s.output[s.outcnt] = bytes1(uint8(symbol));
s.outcnt++;
} else if (symbol > 256) {
uint256 tempBits;
// Length
// Get and compute length
symbol -= 257;
if (symbol >= 29) {
// Invalid fixed code
return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE;
}
(err, tempBits) = bits(s, lext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
len = lens[symbol] + tempBits;
// Get and check distance
(err, symbol) = _decode(s, distcode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
(err, tempBits) = bits(s, dext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
dist = dists[symbol] + tempBits;
if (dist > s.outcnt) {
// Distance too far back
return ErrorCode.ERR_DISTANCE_TOO_FAR;
}
// Copy length bytes from distance bytes back
if (s.outcnt + len > s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt] = s.output[s.outcnt - dist];
s.outcnt++;
}
} else {
s.outcnt += len;
}
}
// Done with a valid fixed or dynamic block
return ErrorCode.ERR_NONE;
}
function _build_fixed(State memory s) private pure returns (ErrorCode) {
// Build fixed Huffman tables
// TODO this is all a compile-time constant
uint256 symbol;
uint256[] memory lengths = new uint256[](FIXLCODES);
// Literal/length table
for (symbol = 0; symbol < 144; symbol++) {
lengths[symbol] = 8;
}
for (; symbol < 256; symbol++) {
lengths[symbol] = 9;
}
for (; symbol < 280; symbol++) {
lengths[symbol] = 7;
}
for (; symbol < FIXLCODES; symbol++) {
lengths[symbol] = 8;
}
_construct(s.lencode, lengths, FIXLCODES, 0);
// Distance table
for (symbol = 0; symbol < MAXDCODES; symbol++) {
lengths[symbol] = 5;
}
_construct(s.distcode, lengths, MAXDCODES, 0);
return ErrorCode.ERR_NONE;
}
function _fixed(State memory s) private pure returns (ErrorCode) {
// Decode data until end-of-block code
return _codes(s, s.lencode, s.distcode);
}
function _build_dynamic_lengths(State memory s)
private
pure
returns (ErrorCode, uint256[] memory)
{
uint256 ncode;
// Index of lengths[]
uint256 index;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Error code
ErrorCode err;
// Permutation of code length codes
uint8[19] memory order =
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
(err, ncode) = bits(s, 4);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
ncode += 4;
// Read code length code lengths (really), missing lengths are zero
for (index = 0; index < ncode; index++) {
(err, lengths[order[index]]) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
}
for (; index < 19; index++) {
lengths[order[index]] = 0;
}
return (ErrorCode.ERR_NONE, lengths);
}
function _build_dynamic(State memory s)
private
pure
returns (
ErrorCode,
Huffman memory,
Huffman memory
)
{
// Number of lengths in descriptor
uint256 nlen;
uint256 ndist;
// Index of lengths[]
uint256 index;
// Error code
ErrorCode err;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Length and distance codes
Huffman memory lencode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXLCODES));
Huffman memory distcode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES));
uint256 tempBits;
// Get number of lengths in each table, check lengths
(err, nlen) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
nlen += 257;
(err, ndist) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
ndist += 1;
if (nlen > MAXLCODES || ndist > MAXDCODES) {
// Bad counts
return (
ErrorCode.ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES,
lencode,
distcode
);
}
(err, lengths) = _build_dynamic_lengths(s);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
// Build huffman table for code lengths codes (use lencode temporarily)
err = _construct(lencode, lengths, 19, 0);
if (err != ErrorCode.ERR_NONE) {
// Require complete code set here
return (
ErrorCode.ERR_CODE_LENGTHS_CODES_INCOMPLETE,
lencode,
distcode
);
}
// Read length/literal and distance code length tables
index = 0;
while (index < nlen + ndist) {
// Decoded value
uint256 symbol;
// Last length to repeat
uint256 len;
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return (err, lencode, distcode);
}
if (symbol < 16) {
// Length in 0..15
lengths[index++] = symbol;
} else {
// Repeat instruction
// Assume repeating zeros
len = 0;
if (symbol == 16) {
// Repeat last length 3..6 times
if (index == 0) {
// No last length!
return (
ErrorCode.ERR_REPEAT_NO_FIRST_LENGTH,
lencode,
distcode
);
}
// Last length
len = lengths[index - 1];
(err, tempBits) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else if (symbol == 17) {
// Repeat zero 3..10 times
(err, tempBits) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else {
// == 18, repeat zero 11..138 times
(err, tempBits) = bits(s, 7);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 11 + tempBits;
}
if (index + symbol > nlen + ndist) {
// Too many lengths!
return (ErrorCode.ERR_REPEAT_MORE, lencode, distcode);
}
while (symbol != 0) {
// Note: Solidity reverts on underflow, so we decrement here
symbol -= 1;
// Repeat last or zero symbol times
lengths[index++] = len;
}
}
}
// Check for end-of-block code -- there better be one!
if (lengths[256] == 0) {
return (ErrorCode.ERR_MISSING_END_OF_BLOCK, lencode, distcode);
}
// Build huffman table for literal/length codes
err = _construct(lencode, lengths, nlen, 0);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
nlen != lencode.counts[0] + lencode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS,
lencode,
distcode
);
}
// Build huffman table for distance codes
err = _construct(distcode, lengths, ndist, nlen);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
ndist != distcode.counts[0] + distcode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_DISTANCE_CODE_LENGTHS,
lencode,
distcode
);
}
return (ErrorCode.ERR_NONE, lencode, distcode);
}
function _dynamic(State memory s) private pure returns (ErrorCode) {
// Length and distance codes
Huffman memory lencode;
Huffman memory distcode;
// Error code
ErrorCode err;
(err, lencode, distcode) = _build_dynamic(s);
if (err != ErrorCode.ERR_NONE) {
return err;
}
// Decode data until end-of-block code
return _codes(s, lencode, distcode);
}
function puff(bytes calldata source, uint256 destlen)
internal
pure
returns (ErrorCode, bytes memory)
{
// Input/output state
State memory s =
State(
new bytes(destlen),
0,
source,
0,
0,
0,
Huffman(new uint256[](MAXBITS + 1), new uint256[](FIXLCODES)),
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES))
);
// Temp: last bit
uint256 last;
// Temp: block type bit
uint256 t;
// Error code
ErrorCode err;
// Build fixed Huffman tables
err = _build_fixed(s);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Process blocks until last block or error
while (last == 0) {
// One if last block
(err, last) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Block type 0..3
(err, t) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
err = (
t == 0
? _stored(s)
: (
t == 1
? _fixed(s)
: (
t == 2
? _dynamic(s)
: ErrorCode.ERR_INVALID_BLOCK_TYPE
)
)
);
// type == 3, invalid
if (err != ErrorCode.ERR_NONE) {
// Return with error
break;
}
}
return (err, s.output);
}
}
| Return need bits, zeroing the bits above that | uint256 ret = (val & ((1 << need) - 1));
| 2,473,960 | [
1,
990,
1608,
4125,
16,
3634,
310,
326,
4125,
5721,
716,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
325,
273,
261,
1125,
473,
14015,
21,
2296,
1608,
13,
300,
404,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-23
*/
/**
*Submitted for verification at Etherscan.io on 2020-08-03
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.10;
pragma experimental ABIEncoderV2;
/**
* @title The Open Oracle Data Base Contract
* @author Compound Labs, Inc.
*/
contract OpenOracleData {
/**
* @notice The event emitted when a source writes to its storage
*/
//event Write(address indexed source, <Key> indexed key, string kind, uint64 timestamp, <Value> value);
/**
* @notice Write a bunch of signed datum to the authenticated storage mapping
* @param message The payload containing the timestamp, and (key, value) pairs
* @param signature The cryptographic signature of the message payload, authorizing the source to write
* @return The keys that were written
*/
//function put(bytes calldata message, bytes calldata signature) external returns (<Key> memory);
/**
* @notice Read a single key with a pre-defined type signature from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The claimed Unix timestamp for the data and the encoded value (defaults to (0, 0x))
*/
//function get(address source, <Key> key) external view returns (uint, <Value>);
/**
* @notice Recovers the source address which signed a message
* @dev Comparing to a claimed address would add nothing,
* as the caller could simply perform the recover and claim that address.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
* @return The source address which signed the message, presumably
*/
function source(bytes memory message, bytes memory signature) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message)));
return ecrecover(hash, v, r, s);
}
}
/**
* @title The Open Oracle Price Data Contract
* @notice Values stored in this contract should represent a USD price with 6 decimals precision
* @author Compound Labs, Inc.
*/
contract OpenOraclePriceData is OpenOracleData {
///@notice The event emitted when a source writes to its storage
event Write(address indexed source, string key, uint64 timestamp, uint64 value);
///@notice The event emitted when the timestamp on a price is invalid and it is not written to storage
event NotWritten(uint64 priorTimestamp, uint256 messageTimestamp, uint256 blockTimestamp);
///@notice The fundamental unit of storage for a reporter source
struct Datum {
uint64 timestamp;
uint64 value;
}
/**
* @dev The most recent authenticated data from all sources.
* This is private because dynamic mapping keys preclude auto-generated getters.
*/
mapping(address => mapping(string => Datum)) private data;
/**
* @notice Write a bunch of signed datum to the authenticated storage mapping
* @param message The payload containing the timestamp, and (key, value) pairs
* @param signature The cryptographic signature of the message payload, authorizing the source to write
* @return The keys that were written
*/
function put(bytes calldata message, bytes calldata signature) external returns (string memory) {
(address source, uint64 timestamp, string memory key, uint64 value) = decodeMessage(message, signature);
return putInternal(source, timestamp, key, value);
}
function putInternal(address source, uint64 timestamp, string memory key, uint64 value) internal returns (string memory) {
// Only update if newer than stored, according to source
Datum storage prior = data[source][key];
if (timestamp > prior.timestamp && timestamp < block.timestamp + 60 minutes && source != address(0)) {
data[source][key] = Datum(timestamp, value);
emit Write(source, key, timestamp, value);
} else {
emit NotWritten(prior.timestamp, timestamp, block.timestamp);
}
return key;
}
function decodeMessage(bytes calldata message, bytes calldata signature) internal pure returns (address, uint64, string memory, uint64) {
// Recover the source address
address source = source(message, signature);
// Decode the message and check the kind
(string memory kind, uint64 timestamp, string memory key, uint64 value) = abi.decode(message, (string, uint64, string, uint64));
require(keccak256(abi.encodePacked(kind)) == keccak256(abi.encodePacked("prices")), "Kind of data must be 'prices'");
return (source, timestamp, key, value);
}
/**
* @notice Read a single key from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The claimed Unix timestamp for the data and the price value (defaults to (0, 0))
*/
function get(address source, string calldata key) external view returns (uint64, uint64) {
Datum storage datum = data[source][key];
return (datum.timestamp, datum.value);
}
/**
* @notice Read only the value for a single key from an authenticated source
* @param source The verifiable author of the data
* @param key The selector for the value to return
* @return The price value (defaults to 0)
*/
function getPrice(address source, string calldata key) external view returns (uint64) {
return data[source][key].value;
}
}
interface CErc20 {
function underlying() external view returns (address);
}
contract UniswapConfig {
/// @dev Describe how to interpret the fixedPrice in the TokenConfig.
enum PriceSource {
FIXED_ETH, /// implies the fixedPrice is a constant multiple of the ETH price (which varies)
FIXED_USD, /// implies the fixedPrice is a constant multiple of the USD price (which is 1)
REPORTER /// implies the price is set by the reporter
}
/// @dev Describe how the USD price should be determined for an asset.
/// There should be 1 TokenConfig object for each supported asset, passed in the constructor.
struct TokenConfig {
address cToken;
address underlying;
bytes32 symbolHash;
uint256 baseUnit;
PriceSource priceSource;
uint256 fixedPrice;
address uniswapMarket;
bool isUniswapReversed;
}
/// @notice The max number of tokens this contract is hardcoded to support
/// @dev Do not change this variable without updating all the fields throughout the contract.
uint public constant maxTokens = 30;
/// @notice The number of tokens this contract actually supports
uint public immutable numTokens;
address internal immutable cToken00;
address internal immutable cToken01;
address internal immutable cToken02;
address internal immutable cToken03;
address internal immutable cToken04;
address internal immutable cToken05;
address internal immutable cToken06;
address internal immutable cToken07;
address internal immutable cToken08;
address internal immutable cToken09;
address internal immutable cToken10;
address internal immutable cToken11;
address internal immutable cToken12;
address internal immutable cToken13;
address internal immutable cToken14;
address internal immutable cToken15;
address internal immutable cToken16;
address internal immutable cToken17;
address internal immutable cToken18;
address internal immutable cToken19;
address internal immutable cToken20;
address internal immutable cToken21;
address internal immutable cToken22;
address internal immutable cToken23;
address internal immutable cToken24;
address internal immutable cToken25;
address internal immutable cToken26;
address internal immutable cToken27;
address internal immutable cToken28;
address internal immutable cToken29;
address internal immutable underlying00;
address internal immutable underlying01;
address internal immutable underlying02;
address internal immutable underlying03;
address internal immutable underlying04;
address internal immutable underlying05;
address internal immutable underlying06;
address internal immutable underlying07;
address internal immutable underlying08;
address internal immutable underlying09;
address internal immutable underlying10;
address internal immutable underlying11;
address internal immutable underlying12;
address internal immutable underlying13;
address internal immutable underlying14;
address internal immutable underlying15;
address internal immutable underlying16;
address internal immutable underlying17;
address internal immutable underlying18;
address internal immutable underlying19;
address internal immutable underlying20;
address internal immutable underlying21;
address internal immutable underlying22;
address internal immutable underlying23;
address internal immutable underlying24;
address internal immutable underlying25;
address internal immutable underlying26;
address internal immutable underlying27;
address internal immutable underlying28;
address internal immutable underlying29;
bytes32 internal immutable symbolHash00;
bytes32 internal immutable symbolHash01;
bytes32 internal immutable symbolHash02;
bytes32 internal immutable symbolHash03;
bytes32 internal immutable symbolHash04;
bytes32 internal immutable symbolHash05;
bytes32 internal immutable symbolHash06;
bytes32 internal immutable symbolHash07;
bytes32 internal immutable symbolHash08;
bytes32 internal immutable symbolHash09;
bytes32 internal immutable symbolHash10;
bytes32 internal immutable symbolHash11;
bytes32 internal immutable symbolHash12;
bytes32 internal immutable symbolHash13;
bytes32 internal immutable symbolHash14;
bytes32 internal immutable symbolHash15;
bytes32 internal immutable symbolHash16;
bytes32 internal immutable symbolHash17;
bytes32 internal immutable symbolHash18;
bytes32 internal immutable symbolHash19;
bytes32 internal immutable symbolHash20;
bytes32 internal immutable symbolHash21;
bytes32 internal immutable symbolHash22;
bytes32 internal immutable symbolHash23;
bytes32 internal immutable symbolHash24;
bytes32 internal immutable symbolHash25;
bytes32 internal immutable symbolHash26;
bytes32 internal immutable symbolHash27;
bytes32 internal immutable symbolHash28;
bytes32 internal immutable symbolHash29;
uint256 internal immutable baseUnit00;
uint256 internal immutable baseUnit01;
uint256 internal immutable baseUnit02;
uint256 internal immutable baseUnit03;
uint256 internal immutable baseUnit04;
uint256 internal immutable baseUnit05;
uint256 internal immutable baseUnit06;
uint256 internal immutable baseUnit07;
uint256 internal immutable baseUnit08;
uint256 internal immutable baseUnit09;
uint256 internal immutable baseUnit10;
uint256 internal immutable baseUnit11;
uint256 internal immutable baseUnit12;
uint256 internal immutable baseUnit13;
uint256 internal immutable baseUnit14;
uint256 internal immutable baseUnit15;
uint256 internal immutable baseUnit16;
uint256 internal immutable baseUnit17;
uint256 internal immutable baseUnit18;
uint256 internal immutable baseUnit19;
uint256 internal immutable baseUnit20;
uint256 internal immutable baseUnit21;
uint256 internal immutable baseUnit22;
uint256 internal immutable baseUnit23;
uint256 internal immutable baseUnit24;
uint256 internal immutable baseUnit25;
uint256 internal immutable baseUnit26;
uint256 internal immutable baseUnit27;
uint256 internal immutable baseUnit28;
uint256 internal immutable baseUnit29;
PriceSource internal immutable priceSource00;
PriceSource internal immutable priceSource01;
PriceSource internal immutable priceSource02;
PriceSource internal immutable priceSource03;
PriceSource internal immutable priceSource04;
PriceSource internal immutable priceSource05;
PriceSource internal immutable priceSource06;
PriceSource internal immutable priceSource07;
PriceSource internal immutable priceSource08;
PriceSource internal immutable priceSource09;
PriceSource internal immutable priceSource10;
PriceSource internal immutable priceSource11;
PriceSource internal immutable priceSource12;
PriceSource internal immutable priceSource13;
PriceSource internal immutable priceSource14;
PriceSource internal immutable priceSource15;
PriceSource internal immutable priceSource16;
PriceSource internal immutable priceSource17;
PriceSource internal immutable priceSource18;
PriceSource internal immutable priceSource19;
PriceSource internal immutable priceSource20;
PriceSource internal immutable priceSource21;
PriceSource internal immutable priceSource22;
PriceSource internal immutable priceSource23;
PriceSource internal immutable priceSource24;
PriceSource internal immutable priceSource25;
PriceSource internal immutable priceSource26;
PriceSource internal immutable priceSource27;
PriceSource internal immutable priceSource28;
PriceSource internal immutable priceSource29;
uint256 internal immutable fixedPrice00;
uint256 internal immutable fixedPrice01;
uint256 internal immutable fixedPrice02;
uint256 internal immutable fixedPrice03;
uint256 internal immutable fixedPrice04;
uint256 internal immutable fixedPrice05;
uint256 internal immutable fixedPrice06;
uint256 internal immutable fixedPrice07;
uint256 internal immutable fixedPrice08;
uint256 internal immutable fixedPrice09;
uint256 internal immutable fixedPrice10;
uint256 internal immutable fixedPrice11;
uint256 internal immutable fixedPrice12;
uint256 internal immutable fixedPrice13;
uint256 internal immutable fixedPrice14;
uint256 internal immutable fixedPrice15;
uint256 internal immutable fixedPrice16;
uint256 internal immutable fixedPrice17;
uint256 internal immutable fixedPrice18;
uint256 internal immutable fixedPrice19;
uint256 internal immutable fixedPrice20;
uint256 internal immutable fixedPrice21;
uint256 internal immutable fixedPrice22;
uint256 internal immutable fixedPrice23;
uint256 internal immutable fixedPrice24;
uint256 internal immutable fixedPrice25;
uint256 internal immutable fixedPrice26;
uint256 internal immutable fixedPrice27;
uint256 internal immutable fixedPrice28;
uint256 internal immutable fixedPrice29;
address internal immutable uniswapMarket00;
address internal immutable uniswapMarket01;
address internal immutable uniswapMarket02;
address internal immutable uniswapMarket03;
address internal immutable uniswapMarket04;
address internal immutable uniswapMarket05;
address internal immutable uniswapMarket06;
address internal immutable uniswapMarket07;
address internal immutable uniswapMarket08;
address internal immutable uniswapMarket09;
address internal immutable uniswapMarket10;
address internal immutable uniswapMarket11;
address internal immutable uniswapMarket12;
address internal immutable uniswapMarket13;
address internal immutable uniswapMarket14;
address internal immutable uniswapMarket15;
address internal immutable uniswapMarket16;
address internal immutable uniswapMarket17;
address internal immutable uniswapMarket18;
address internal immutable uniswapMarket19;
address internal immutable uniswapMarket20;
address internal immutable uniswapMarket21;
address internal immutable uniswapMarket22;
address internal immutable uniswapMarket23;
address internal immutable uniswapMarket24;
address internal immutable uniswapMarket25;
address internal immutable uniswapMarket26;
address internal immutable uniswapMarket27;
address internal immutable uniswapMarket28;
address internal immutable uniswapMarket29;
bool internal immutable isUniswapReversed00;
bool internal immutable isUniswapReversed01;
bool internal immutable isUniswapReversed02;
bool internal immutable isUniswapReversed03;
bool internal immutable isUniswapReversed04;
bool internal immutable isUniswapReversed05;
bool internal immutable isUniswapReversed06;
bool internal immutable isUniswapReversed07;
bool internal immutable isUniswapReversed08;
bool internal immutable isUniswapReversed09;
bool internal immutable isUniswapReversed10;
bool internal immutable isUniswapReversed11;
bool internal immutable isUniswapReversed12;
bool internal immutable isUniswapReversed13;
bool internal immutable isUniswapReversed14;
bool internal immutable isUniswapReversed15;
bool internal immutable isUniswapReversed16;
bool internal immutable isUniswapReversed17;
bool internal immutable isUniswapReversed18;
bool internal immutable isUniswapReversed19;
bool internal immutable isUniswapReversed20;
bool internal immutable isUniswapReversed21;
bool internal immutable isUniswapReversed22;
bool internal immutable isUniswapReversed23;
bool internal immutable isUniswapReversed24;
bool internal immutable isUniswapReversed25;
bool internal immutable isUniswapReversed26;
bool internal immutable isUniswapReversed27;
bool internal immutable isUniswapReversed28;
bool internal immutable isUniswapReversed29;
/**
* @notice Construct an immutable store of configs into the contract data
* @param configs The configs for the supported assets
*/
constructor(TokenConfig[] memory configs) public {
require(configs.length <= maxTokens, "too many configs");
numTokens = configs.length;
cToken00 = get(configs, 0).cToken;
cToken01 = get(configs, 1).cToken;
cToken02 = get(configs, 2).cToken;
cToken03 = get(configs, 3).cToken;
cToken04 = get(configs, 4).cToken;
cToken05 = get(configs, 5).cToken;
cToken06 = get(configs, 6).cToken;
cToken07 = get(configs, 7).cToken;
cToken08 = get(configs, 8).cToken;
cToken09 = get(configs, 9).cToken;
cToken10 = get(configs, 10).cToken;
cToken11 = get(configs, 11).cToken;
cToken12 = get(configs, 12).cToken;
cToken13 = get(configs, 13).cToken;
cToken14 = get(configs, 14).cToken;
cToken15 = get(configs, 15).cToken;
cToken16 = get(configs, 16).cToken;
cToken17 = get(configs, 17).cToken;
cToken18 = get(configs, 18).cToken;
cToken19 = get(configs, 19).cToken;
cToken20 = get(configs, 20).cToken;
cToken21 = get(configs, 21).cToken;
cToken22 = get(configs, 22).cToken;
cToken23 = get(configs, 23).cToken;
cToken24 = get(configs, 24).cToken;
cToken25 = get(configs, 25).cToken;
cToken26 = get(configs, 26).cToken;
cToken27 = get(configs, 27).cToken;
cToken28 = get(configs, 28).cToken;
cToken29 = get(configs, 29).cToken;
underlying00 = get(configs, 0).underlying;
underlying01 = get(configs, 1).underlying;
underlying02 = get(configs, 2).underlying;
underlying03 = get(configs, 3).underlying;
underlying04 = get(configs, 4).underlying;
underlying05 = get(configs, 5).underlying;
underlying06 = get(configs, 6).underlying;
underlying07 = get(configs, 7).underlying;
underlying08 = get(configs, 8).underlying;
underlying09 = get(configs, 9).underlying;
underlying10 = get(configs, 10).underlying;
underlying11 = get(configs, 11).underlying;
underlying12 = get(configs, 12).underlying;
underlying13 = get(configs, 13).underlying;
underlying14 = get(configs, 14).underlying;
underlying15 = get(configs, 15).underlying;
underlying16 = get(configs, 16).underlying;
underlying17 = get(configs, 17).underlying;
underlying18 = get(configs, 18).underlying;
underlying19 = get(configs, 19).underlying;
underlying20 = get(configs, 20).underlying;
underlying21 = get(configs, 21).underlying;
underlying22 = get(configs, 22).underlying;
underlying23 = get(configs, 23).underlying;
underlying24 = get(configs, 24).underlying;
underlying25 = get(configs, 25).underlying;
underlying26 = get(configs, 26).underlying;
underlying27 = get(configs, 27).underlying;
underlying28 = get(configs, 28).underlying;
underlying29 = get(configs, 29).underlying;
symbolHash00 = get(configs, 0).symbolHash;
symbolHash01 = get(configs, 1).symbolHash;
symbolHash02 = get(configs, 2).symbolHash;
symbolHash03 = get(configs, 3).symbolHash;
symbolHash04 = get(configs, 4).symbolHash;
symbolHash05 = get(configs, 5).symbolHash;
symbolHash06 = get(configs, 6).symbolHash;
symbolHash07 = get(configs, 7).symbolHash;
symbolHash08 = get(configs, 8).symbolHash;
symbolHash09 = get(configs, 9).symbolHash;
symbolHash10 = get(configs, 10).symbolHash;
symbolHash11 = get(configs, 11).symbolHash;
symbolHash12 = get(configs, 12).symbolHash;
symbolHash13 = get(configs, 13).symbolHash;
symbolHash14 = get(configs, 14).symbolHash;
symbolHash15 = get(configs, 15).symbolHash;
symbolHash16 = get(configs, 16).symbolHash;
symbolHash17 = get(configs, 17).symbolHash;
symbolHash18 = get(configs, 18).symbolHash;
symbolHash19 = get(configs, 19).symbolHash;
symbolHash20 = get(configs, 20).symbolHash;
symbolHash21 = get(configs, 21).symbolHash;
symbolHash22 = get(configs, 22).symbolHash;
symbolHash23 = get(configs, 23).symbolHash;
symbolHash24 = get(configs, 24).symbolHash;
symbolHash25 = get(configs, 25).symbolHash;
symbolHash26 = get(configs, 26).symbolHash;
symbolHash27 = get(configs, 27).symbolHash;
symbolHash28 = get(configs, 28).symbolHash;
symbolHash29 = get(configs, 29).symbolHash;
baseUnit00 = get(configs, 0).baseUnit;
baseUnit01 = get(configs, 1).baseUnit;
baseUnit02 = get(configs, 2).baseUnit;
baseUnit03 = get(configs, 3).baseUnit;
baseUnit04 = get(configs, 4).baseUnit;
baseUnit05 = get(configs, 5).baseUnit;
baseUnit06 = get(configs, 6).baseUnit;
baseUnit07 = get(configs, 7).baseUnit;
baseUnit08 = get(configs, 8).baseUnit;
baseUnit09 = get(configs, 9).baseUnit;
baseUnit10 = get(configs, 10).baseUnit;
baseUnit11 = get(configs, 11).baseUnit;
baseUnit12 = get(configs, 12).baseUnit;
baseUnit13 = get(configs, 13).baseUnit;
baseUnit14 = get(configs, 14).baseUnit;
baseUnit15 = get(configs, 15).baseUnit;
baseUnit16 = get(configs, 16).baseUnit;
baseUnit17 = get(configs, 17).baseUnit;
baseUnit18 = get(configs, 18).baseUnit;
baseUnit19 = get(configs, 19).baseUnit;
baseUnit20 = get(configs, 20).baseUnit;
baseUnit21 = get(configs, 21).baseUnit;
baseUnit22 = get(configs, 22).baseUnit;
baseUnit23 = get(configs, 23).baseUnit;
baseUnit24 = get(configs, 24).baseUnit;
baseUnit25 = get(configs, 25).baseUnit;
baseUnit26 = get(configs, 26).baseUnit;
baseUnit27 = get(configs, 27).baseUnit;
baseUnit28 = get(configs, 28).baseUnit;
baseUnit29 = get(configs, 29).baseUnit;
priceSource00 = get(configs, 0).priceSource;
priceSource01 = get(configs, 1).priceSource;
priceSource02 = get(configs, 2).priceSource;
priceSource03 = get(configs, 3).priceSource;
priceSource04 = get(configs, 4).priceSource;
priceSource05 = get(configs, 5).priceSource;
priceSource06 = get(configs, 6).priceSource;
priceSource07 = get(configs, 7).priceSource;
priceSource08 = get(configs, 8).priceSource;
priceSource09 = get(configs, 9).priceSource;
priceSource10 = get(configs, 10).priceSource;
priceSource11 = get(configs, 11).priceSource;
priceSource12 = get(configs, 12).priceSource;
priceSource13 = get(configs, 13).priceSource;
priceSource14 = get(configs, 14).priceSource;
priceSource15 = get(configs, 15).priceSource;
priceSource16 = get(configs, 16).priceSource;
priceSource17 = get(configs, 17).priceSource;
priceSource18 = get(configs, 18).priceSource;
priceSource19 = get(configs, 19).priceSource;
priceSource20 = get(configs, 20).priceSource;
priceSource21 = get(configs, 21).priceSource;
priceSource22 = get(configs, 22).priceSource;
priceSource23 = get(configs, 23).priceSource;
priceSource24 = get(configs, 24).priceSource;
priceSource25 = get(configs, 25).priceSource;
priceSource26 = get(configs, 26).priceSource;
priceSource27 = get(configs, 27).priceSource;
priceSource28 = get(configs, 28).priceSource;
priceSource29 = get(configs, 29).priceSource;
fixedPrice00 = get(configs, 0).fixedPrice;
fixedPrice01 = get(configs, 1).fixedPrice;
fixedPrice02 = get(configs, 2).fixedPrice;
fixedPrice03 = get(configs, 3).fixedPrice;
fixedPrice04 = get(configs, 4).fixedPrice;
fixedPrice05 = get(configs, 5).fixedPrice;
fixedPrice06 = get(configs, 6).fixedPrice;
fixedPrice07 = get(configs, 7).fixedPrice;
fixedPrice08 = get(configs, 8).fixedPrice;
fixedPrice09 = get(configs, 9).fixedPrice;
fixedPrice10 = get(configs, 10).fixedPrice;
fixedPrice11 = get(configs, 11).fixedPrice;
fixedPrice12 = get(configs, 12).fixedPrice;
fixedPrice13 = get(configs, 13).fixedPrice;
fixedPrice14 = get(configs, 14).fixedPrice;
fixedPrice15 = get(configs, 15).fixedPrice;
fixedPrice16 = get(configs, 16).fixedPrice;
fixedPrice17 = get(configs, 17).fixedPrice;
fixedPrice18 = get(configs, 18).fixedPrice;
fixedPrice19 = get(configs, 19).fixedPrice;
fixedPrice20 = get(configs, 20).fixedPrice;
fixedPrice21 = get(configs, 21).fixedPrice;
fixedPrice22 = get(configs, 22).fixedPrice;
fixedPrice23 = get(configs, 23).fixedPrice;
fixedPrice24 = get(configs, 24).fixedPrice;
fixedPrice25 = get(configs, 25).fixedPrice;
fixedPrice26 = get(configs, 26).fixedPrice;
fixedPrice27 = get(configs, 27).fixedPrice;
fixedPrice28 = get(configs, 28).fixedPrice;
fixedPrice29 = get(configs, 29).fixedPrice;
uniswapMarket00 = get(configs, 0).uniswapMarket;
uniswapMarket01 = get(configs, 1).uniswapMarket;
uniswapMarket02 = get(configs, 2).uniswapMarket;
uniswapMarket03 = get(configs, 3).uniswapMarket;
uniswapMarket04 = get(configs, 4).uniswapMarket;
uniswapMarket05 = get(configs, 5).uniswapMarket;
uniswapMarket06 = get(configs, 6).uniswapMarket;
uniswapMarket07 = get(configs, 7).uniswapMarket;
uniswapMarket08 = get(configs, 8).uniswapMarket;
uniswapMarket09 = get(configs, 9).uniswapMarket;
uniswapMarket10 = get(configs, 10).uniswapMarket;
uniswapMarket11 = get(configs, 11).uniswapMarket;
uniswapMarket12 = get(configs, 12).uniswapMarket;
uniswapMarket13 = get(configs, 13).uniswapMarket;
uniswapMarket14 = get(configs, 14).uniswapMarket;
uniswapMarket15 = get(configs, 15).uniswapMarket;
uniswapMarket16 = get(configs, 16).uniswapMarket;
uniswapMarket17 = get(configs, 17).uniswapMarket;
uniswapMarket18 = get(configs, 18).uniswapMarket;
uniswapMarket19 = get(configs, 19).uniswapMarket;
uniswapMarket20 = get(configs, 20).uniswapMarket;
uniswapMarket21 = get(configs, 21).uniswapMarket;
uniswapMarket22 = get(configs, 22).uniswapMarket;
uniswapMarket23 = get(configs, 23).uniswapMarket;
uniswapMarket24 = get(configs, 24).uniswapMarket;
uniswapMarket25 = get(configs, 25).uniswapMarket;
uniswapMarket26 = get(configs, 26).uniswapMarket;
uniswapMarket27 = get(configs, 27).uniswapMarket;
uniswapMarket28 = get(configs, 28).uniswapMarket;
uniswapMarket29 = get(configs, 29).uniswapMarket;
isUniswapReversed00 = get(configs, 0).isUniswapReversed;
isUniswapReversed01 = get(configs, 1).isUniswapReversed;
isUniswapReversed02 = get(configs, 2).isUniswapReversed;
isUniswapReversed03 = get(configs, 3).isUniswapReversed;
isUniswapReversed04 = get(configs, 4).isUniswapReversed;
isUniswapReversed05 = get(configs, 5).isUniswapReversed;
isUniswapReversed06 = get(configs, 6).isUniswapReversed;
isUniswapReversed07 = get(configs, 7).isUniswapReversed;
isUniswapReversed08 = get(configs, 8).isUniswapReversed;
isUniswapReversed09 = get(configs, 9).isUniswapReversed;
isUniswapReversed10 = get(configs, 10).isUniswapReversed;
isUniswapReversed11 = get(configs, 11).isUniswapReversed;
isUniswapReversed12 = get(configs, 12).isUniswapReversed;
isUniswapReversed13 = get(configs, 13).isUniswapReversed;
isUniswapReversed14 = get(configs, 14).isUniswapReversed;
isUniswapReversed15 = get(configs, 15).isUniswapReversed;
isUniswapReversed16 = get(configs, 16).isUniswapReversed;
isUniswapReversed17 = get(configs, 17).isUniswapReversed;
isUniswapReversed18 = get(configs, 18).isUniswapReversed;
isUniswapReversed19 = get(configs, 19).isUniswapReversed;
isUniswapReversed20 = get(configs, 20).isUniswapReversed;
isUniswapReversed21 = get(configs, 21).isUniswapReversed;
isUniswapReversed22 = get(configs, 22).isUniswapReversed;
isUniswapReversed23 = get(configs, 23).isUniswapReversed;
isUniswapReversed24 = get(configs, 24).isUniswapReversed;
isUniswapReversed25 = get(configs, 25).isUniswapReversed;
isUniswapReversed26 = get(configs, 26).isUniswapReversed;
isUniswapReversed27 = get(configs, 27).isUniswapReversed;
isUniswapReversed28 = get(configs, 28).isUniswapReversed;
isUniswapReversed29 = get(configs, 29).isUniswapReversed;
}
function get(TokenConfig[] memory configs, uint i) internal pure returns (TokenConfig memory) {
if (i < configs.length)
return configs[i];
return TokenConfig({
cToken: address(0),
underlying: address(0),
symbolHash: bytes32(0),
baseUnit: uint256(0),
priceSource: PriceSource(0),
fixedPrice: uint256(0),
uniswapMarket: address(0),
isUniswapReversed: false
});
}
function getCTokenIndex(address cToken) internal view returns (uint) {
if (cToken == cToken00) return 0;
if (cToken == cToken01) return 1;
if (cToken == cToken02) return 2;
if (cToken == cToken03) return 3;
if (cToken == cToken04) return 4;
if (cToken == cToken05) return 5;
if (cToken == cToken06) return 6;
if (cToken == cToken07) return 7;
if (cToken == cToken08) return 8;
if (cToken == cToken09) return 9;
if (cToken == cToken10) return 10;
if (cToken == cToken11) return 11;
if (cToken == cToken12) return 12;
if (cToken == cToken13) return 13;
if (cToken == cToken14) return 14;
if (cToken == cToken15) return 15;
if (cToken == cToken16) return 16;
if (cToken == cToken17) return 17;
if (cToken == cToken18) return 18;
if (cToken == cToken19) return 19;
if (cToken == cToken20) return 20;
if (cToken == cToken21) return 21;
if (cToken == cToken22) return 22;
if (cToken == cToken23) return 23;
if (cToken == cToken24) return 24;
if (cToken == cToken25) return 25;
if (cToken == cToken26) return 26;
if (cToken == cToken27) return 27;
if (cToken == cToken28) return 28;
if (cToken == cToken29) return 29;
return uint(-1);
}
function getUnderlyingIndex(address underlying) internal view returns (uint) {
if (underlying == underlying00) return 0;
if (underlying == underlying01) return 1;
if (underlying == underlying02) return 2;
if (underlying == underlying03) return 3;
if (underlying == underlying04) return 4;
if (underlying == underlying05) return 5;
if (underlying == underlying06) return 6;
if (underlying == underlying07) return 7;
if (underlying == underlying08) return 8;
if (underlying == underlying09) return 9;
if (underlying == underlying10) return 10;
if (underlying == underlying11) return 11;
if (underlying == underlying12) return 12;
if (underlying == underlying13) return 13;
if (underlying == underlying14) return 14;
if (underlying == underlying15) return 15;
if (underlying == underlying16) return 16;
if (underlying == underlying17) return 17;
if (underlying == underlying18) return 18;
if (underlying == underlying19) return 19;
if (underlying == underlying20) return 20;
if (underlying == underlying21) return 21;
if (underlying == underlying22) return 22;
if (underlying == underlying23) return 23;
if (underlying == underlying24) return 24;
if (underlying == underlying25) return 25;
if (underlying == underlying26) return 26;
if (underlying == underlying27) return 27;
if (underlying == underlying28) return 28;
if (underlying == underlying29) return 29;
return uint(-1);
}
function getSymbolHashIndex(bytes32 symbolHash) internal view returns (uint) {
if (symbolHash == symbolHash00) return 0;
if (symbolHash == symbolHash01) return 1;
if (symbolHash == symbolHash02) return 2;
if (symbolHash == symbolHash03) return 3;
if (symbolHash == symbolHash04) return 4;
if (symbolHash == symbolHash05) return 5;
if (symbolHash == symbolHash06) return 6;
if (symbolHash == symbolHash07) return 7;
if (symbolHash == symbolHash08) return 8;
if (symbolHash == symbolHash09) return 9;
if (symbolHash == symbolHash10) return 10;
if (symbolHash == symbolHash11) return 11;
if (symbolHash == symbolHash12) return 12;
if (symbolHash == symbolHash13) return 13;
if (symbolHash == symbolHash14) return 14;
if (symbolHash == symbolHash15) return 15;
if (symbolHash == symbolHash16) return 16;
if (symbolHash == symbolHash17) return 17;
if (symbolHash == symbolHash18) return 18;
if (symbolHash == symbolHash19) return 19;
if (symbolHash == symbolHash20) return 20;
if (symbolHash == symbolHash21) return 21;
if (symbolHash == symbolHash22) return 22;
if (symbolHash == symbolHash23) return 23;
if (symbolHash == symbolHash24) return 24;
if (symbolHash == symbolHash25) return 25;
if (symbolHash == symbolHash26) return 26;
if (symbolHash == symbolHash27) return 27;
if (symbolHash == symbolHash28) return 28;
if (symbolHash == symbolHash29) return 29;
return uint(-1);
}
/**
* @notice Get the i-th config, according to the order they were passed in originally
* @param i The index of the config to get
* @return The config object
*/
function getTokenConfig(uint i) public view returns (TokenConfig memory) {
require(i < numTokens, "token config not found");
if (i == 0) return TokenConfig({cToken: cToken00, underlying: underlying00, symbolHash: symbolHash00, baseUnit: baseUnit00, priceSource: priceSource00, fixedPrice: fixedPrice00, uniswapMarket: uniswapMarket00, isUniswapReversed: isUniswapReversed00});
if (i == 1) return TokenConfig({cToken: cToken01, underlying: underlying01, symbolHash: symbolHash01, baseUnit: baseUnit01, priceSource: priceSource01, fixedPrice: fixedPrice01, uniswapMarket: uniswapMarket01, isUniswapReversed: isUniswapReversed01});
if (i == 2) return TokenConfig({cToken: cToken02, underlying: underlying02, symbolHash: symbolHash02, baseUnit: baseUnit02, priceSource: priceSource02, fixedPrice: fixedPrice02, uniswapMarket: uniswapMarket02, isUniswapReversed: isUniswapReversed02});
if (i == 3) return TokenConfig({cToken: cToken03, underlying: underlying03, symbolHash: symbolHash03, baseUnit: baseUnit03, priceSource: priceSource03, fixedPrice: fixedPrice03, uniswapMarket: uniswapMarket03, isUniswapReversed: isUniswapReversed03});
if (i == 4) return TokenConfig({cToken: cToken04, underlying: underlying04, symbolHash: symbolHash04, baseUnit: baseUnit04, priceSource: priceSource04, fixedPrice: fixedPrice04, uniswapMarket: uniswapMarket04, isUniswapReversed: isUniswapReversed04});
if (i == 5) return TokenConfig({cToken: cToken05, underlying: underlying05, symbolHash: symbolHash05, baseUnit: baseUnit05, priceSource: priceSource05, fixedPrice: fixedPrice05, uniswapMarket: uniswapMarket05, isUniswapReversed: isUniswapReversed05});
if (i == 6) return TokenConfig({cToken: cToken06, underlying: underlying06, symbolHash: symbolHash06, baseUnit: baseUnit06, priceSource: priceSource06, fixedPrice: fixedPrice06, uniswapMarket: uniswapMarket06, isUniswapReversed: isUniswapReversed06});
if (i == 7) return TokenConfig({cToken: cToken07, underlying: underlying07, symbolHash: symbolHash07, baseUnit: baseUnit07, priceSource: priceSource07, fixedPrice: fixedPrice07, uniswapMarket: uniswapMarket07, isUniswapReversed: isUniswapReversed07});
if (i == 8) return TokenConfig({cToken: cToken08, underlying: underlying08, symbolHash: symbolHash08, baseUnit: baseUnit08, priceSource: priceSource08, fixedPrice: fixedPrice08, uniswapMarket: uniswapMarket08, isUniswapReversed: isUniswapReversed08});
if (i == 9) return TokenConfig({cToken: cToken09, underlying: underlying09, symbolHash: symbolHash09, baseUnit: baseUnit09, priceSource: priceSource09, fixedPrice: fixedPrice09, uniswapMarket: uniswapMarket09, isUniswapReversed: isUniswapReversed09});
if (i == 10) return TokenConfig({cToken: cToken10, underlying: underlying10, symbolHash: symbolHash10, baseUnit: baseUnit10, priceSource: priceSource10, fixedPrice: fixedPrice10, uniswapMarket: uniswapMarket10, isUniswapReversed: isUniswapReversed10});
if (i == 11) return TokenConfig({cToken: cToken11, underlying: underlying11, symbolHash: symbolHash11, baseUnit: baseUnit11, priceSource: priceSource11, fixedPrice: fixedPrice11, uniswapMarket: uniswapMarket11, isUniswapReversed: isUniswapReversed11});
if (i == 12) return TokenConfig({cToken: cToken12, underlying: underlying12, symbolHash: symbolHash12, baseUnit: baseUnit12, priceSource: priceSource12, fixedPrice: fixedPrice12, uniswapMarket: uniswapMarket12, isUniswapReversed: isUniswapReversed12});
if (i == 13) return TokenConfig({cToken: cToken13, underlying: underlying13, symbolHash: symbolHash13, baseUnit: baseUnit13, priceSource: priceSource13, fixedPrice: fixedPrice13, uniswapMarket: uniswapMarket13, isUniswapReversed: isUniswapReversed13});
if (i == 14) return TokenConfig({cToken: cToken14, underlying: underlying14, symbolHash: symbolHash14, baseUnit: baseUnit14, priceSource: priceSource14, fixedPrice: fixedPrice14, uniswapMarket: uniswapMarket14, isUniswapReversed: isUniswapReversed14});
if (i == 15) return TokenConfig({cToken: cToken15, underlying: underlying15, symbolHash: symbolHash15, baseUnit: baseUnit15, priceSource: priceSource15, fixedPrice: fixedPrice15, uniswapMarket: uniswapMarket15, isUniswapReversed: isUniswapReversed15});
if (i == 16) return TokenConfig({cToken: cToken16, underlying: underlying16, symbolHash: symbolHash16, baseUnit: baseUnit16, priceSource: priceSource16, fixedPrice: fixedPrice16, uniswapMarket: uniswapMarket16, isUniswapReversed: isUniswapReversed16});
if (i == 17) return TokenConfig({cToken: cToken17, underlying: underlying17, symbolHash: symbolHash17, baseUnit: baseUnit17, priceSource: priceSource17, fixedPrice: fixedPrice17, uniswapMarket: uniswapMarket17, isUniswapReversed: isUniswapReversed17});
if (i == 18) return TokenConfig({cToken: cToken18, underlying: underlying18, symbolHash: symbolHash18, baseUnit: baseUnit18, priceSource: priceSource18, fixedPrice: fixedPrice18, uniswapMarket: uniswapMarket18, isUniswapReversed: isUniswapReversed18});
if (i == 19) return TokenConfig({cToken: cToken19, underlying: underlying19, symbolHash: symbolHash19, baseUnit: baseUnit19, priceSource: priceSource19, fixedPrice: fixedPrice19, uniswapMarket: uniswapMarket19, isUniswapReversed: isUniswapReversed19});
if (i == 20) return TokenConfig({cToken: cToken20, underlying: underlying20, symbolHash: symbolHash20, baseUnit: baseUnit20, priceSource: priceSource20, fixedPrice: fixedPrice20, uniswapMarket: uniswapMarket20, isUniswapReversed: isUniswapReversed20});
if (i == 21) return TokenConfig({cToken: cToken21, underlying: underlying21, symbolHash: symbolHash21, baseUnit: baseUnit21, priceSource: priceSource21, fixedPrice: fixedPrice21, uniswapMarket: uniswapMarket21, isUniswapReversed: isUniswapReversed21});
if (i == 22) return TokenConfig({cToken: cToken22, underlying: underlying22, symbolHash: symbolHash22, baseUnit: baseUnit22, priceSource: priceSource22, fixedPrice: fixedPrice22, uniswapMarket: uniswapMarket22, isUniswapReversed: isUniswapReversed22});
if (i == 23) return TokenConfig({cToken: cToken23, underlying: underlying23, symbolHash: symbolHash23, baseUnit: baseUnit23, priceSource: priceSource23, fixedPrice: fixedPrice23, uniswapMarket: uniswapMarket23, isUniswapReversed: isUniswapReversed23});
if (i == 24) return TokenConfig({cToken: cToken24, underlying: underlying24, symbolHash: symbolHash24, baseUnit: baseUnit24, priceSource: priceSource24, fixedPrice: fixedPrice24, uniswapMarket: uniswapMarket24, isUniswapReversed: isUniswapReversed24});
if (i == 25) return TokenConfig({cToken: cToken25, underlying: underlying25, symbolHash: symbolHash25, baseUnit: baseUnit25, priceSource: priceSource25, fixedPrice: fixedPrice25, uniswapMarket: uniswapMarket25, isUniswapReversed: isUniswapReversed25});
if (i == 26) return TokenConfig({cToken: cToken26, underlying: underlying26, symbolHash: symbolHash26, baseUnit: baseUnit26, priceSource: priceSource26, fixedPrice: fixedPrice26, uniswapMarket: uniswapMarket26, isUniswapReversed: isUniswapReversed26});
if (i == 27) return TokenConfig({cToken: cToken27, underlying: underlying27, symbolHash: symbolHash27, baseUnit: baseUnit27, priceSource: priceSource27, fixedPrice: fixedPrice27, uniswapMarket: uniswapMarket27, isUniswapReversed: isUniswapReversed27});
if (i == 28) return TokenConfig({cToken: cToken28, underlying: underlying28, symbolHash: symbolHash28, baseUnit: baseUnit28, priceSource: priceSource28, fixedPrice: fixedPrice28, uniswapMarket: uniswapMarket28, isUniswapReversed: isUniswapReversed28});
if (i == 29) return TokenConfig({cToken: cToken29, underlying: underlying29, symbolHash: symbolHash29, baseUnit: baseUnit29, priceSource: priceSource29, fixedPrice: fixedPrice29, uniswapMarket: uniswapMarket29, isUniswapReversed: isUniswapReversed29});
}
/**
* @notice Get the config for symbol
* @param symbol The symbol of the config to get
* @return The config object
*/
function getTokenConfigBySymbol(string memory symbol) public view returns (TokenConfig memory) {
return getTokenConfigBySymbolHash(keccak256(abi.encodePacked(symbol)));
}
/**
* @notice Get the config for the symbolHash
* @param symbolHash The keccack256 of the symbol of the config to get
* @return The config object
*/
function getTokenConfigBySymbolHash(bytes32 symbolHash) public view returns (TokenConfig memory) {
uint index = getSymbolHashIndex(symbolHash);
if (index != uint(-1)) {
return getTokenConfig(index);
}
revert("token config not found");
}
/**
* @notice Get the config for the cToken
* @dev If a config for the cToken is not found, falls back to searching for the underlying.
* @param cToken The address of the cToken of the config to get
* @return The config object
*/
function getTokenConfigByCToken(address cToken) public view returns (TokenConfig memory) {
uint index = getCTokenIndex(cToken);
if (index != uint(-1)) {
return getTokenConfig(index);
}
return getTokenConfigByUnderlying(CErc20(cToken).underlying());
}
/**
* @notice Get the config for an underlying asset
* @param underlying The address of the underlying asset of the config to get
* @return The config object
*/
function getTokenConfigByUnderlying(address underlying) public view returns (TokenConfig memory) {
uint index = getUnderlyingIndex(underlying);
if (index != uint(-1)) {
return getTokenConfig(index);
}
revert("token config not found");
}
}
// Based on code from https://github.com/Uniswap/uniswap-v2-periphery
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// returns a uq112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << 112) / denominator);
}
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
// we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
// instead, get close to:
// (x * 1e18) >> 112
// without risk of overflowing, e.g.:
// (x) / 2 ** (112 - lg(1e18))
return uint(self._x) / 5192296858534827;
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
}
struct Observation {
uint timestamp;
uint acc;
}
contract UniswapAnchoredView is UniswapConfig {
using FixedPoint for *;
/// @notice The Open Oracle Price Data contract
OpenOraclePriceData public immutable priceData;
/// @notice The number of wei in 1 ETH
uint public constant ethBaseUnit = 1e18;
/// @notice A common scaling factor to maintain precision
uint public constant expScale = 1e18;
/// @notice The Open Oracle Reporter
address public immutable reporter;
/// @notice The highest ratio of the new price to the anchor price that will still trigger the price to be updated
uint public immutable upperBoundAnchorRatio;
/// @notice The lowest ratio of the new price to the anchor price that will still trigger the price to be updated
uint public immutable lowerBoundAnchorRatio;
/// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced
uint public immutable anchorPeriod;
/// @notice Official prices by symbol hash
mapping(bytes32 => uint) public prices;
/// @notice Circuit breaker for using anchor price oracle directly, ignoring reporter
bool public reporterInvalidated;
/// @notice The old observation for each symbolHash
mapping(bytes32 => Observation) public oldObservations;
/// @notice The new observation for each symbolHash
mapping(bytes32 => Observation) public newObservations;
/// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor
event PriceGuarded(string symbol, uint reporter, uint anchor);
/// @notice The event emitted when the stored price is updated
event PriceUpdated(string symbol, uint price);
/// @notice The event emitted when anchor price is updated
event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp);
/// @notice The event emitted when the uniswap window changes
event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice);
/// @notice The event emitted when reporter invalidates itself
event ReporterInvalidated(address reporter);
bytes32 constant ethHash = keccak256(abi.encodePacked("ETH"));
bytes32 constant rotateHash = keccak256(abi.encodePacked("rotate"));
/**
* @notice Construct a uniswap anchored view for a set of token configurations
* @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using.
* @param reporter_ The reporter whose prices are to be used
* @param anchorToleranceMantissa_ The percentage tolerance that the reporter may deviate from the uniswap anchor
* @param anchorPeriod_ The minimum amount of time required for the old uniswap price accumulator to be replaced
* @param configs The static token configurations which define what prices are supported and how
*/
constructor(OpenOraclePriceData priceData_,
address reporter_,
uint anchorToleranceMantissa_,
uint anchorPeriod_,
TokenConfig[] memory configs) UniswapConfig(configs) public {
priceData = priceData_;
reporter = reporter_;
anchorPeriod = anchorPeriod_;
// Allow the tolerance to be whatever the deployer chooses, but prevent under/overflow (and prices from being 0)
upperBoundAnchorRatio = anchorToleranceMantissa_ > uint(-1) - 100e16 ? uint(-1) : 100e16 + anchorToleranceMantissa_;
lowerBoundAnchorRatio = anchorToleranceMantissa_ < 100e16 ? 100e16 - anchorToleranceMantissa_ : 1;
for (uint i = 0; i < configs.length; i++) {
TokenConfig memory config = configs[i];
require(config.baseUnit > 0, "baseUnit must be greater than zero");
address uniswapMarket = config.uniswapMarket;
if (config.priceSource == PriceSource.REPORTER) {
require(uniswapMarket != address(0), "reported prices must have an anchor");
bytes32 symbolHash = config.symbolHash;
uint cumulativePrice = currentCumulativePrice(config);
oldObservations[symbolHash].timestamp = block.timestamp;
newObservations[symbolHash].timestamp = block.timestamp;
oldObservations[symbolHash].acc = cumulativePrice;
newObservations[symbolHash].acc = cumulativePrice;
emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice);
} else {
require(uniswapMarket == address(0), "only reported prices utilize an anchor");
}
}
}
/**
* @notice Get the official price for a symbol
* @param symbol The symbol to fetch the price of
* @return Price denominated in USD, with 6 decimals
*/
function price(string memory symbol) external view returns (uint) {
TokenConfig memory config = getTokenConfigBySymbol(symbol);
return priceInternal(config);
}
function priceInternal(TokenConfig memory config) internal view returns (uint) {
if (config.priceSource == PriceSource.REPORTER) return prices[config.symbolHash];
if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice;
if (config.priceSource == PriceSource.FIXED_ETH) {
uint usdPerEth = prices[ethHash];
require(usdPerEth > 0, "ETH price not set, cannot convert to dollars");
return mul(usdPerEth, config.fixedPrice) / ethBaseUnit;
}
}
/**
* @notice Get the underlying price of a cToken
* @dev Implements the PriceOracle interface for Compound v2.
* @param cToken The cToken address for price retrieval
* @return Price denominated in USD, with 18 decimals, for the given cToken address
*/
function getUnderlyingPrice(address cToken) external view returns (uint) {
TokenConfig memory config = getTokenConfigByCToken(cToken);
// Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit)
// Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit)
return mul(1e30, priceInternal(config)) / config.baseUnit;
}
/**
* @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor
* @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view.
* @param messages The messages to post to the oracle
* @param signatures The signatures for the corresponding messages
* @param symbols The symbols to compare to anchor for authoritative reading
*/
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external {
require(messages.length == signatures.length, "messages and signatures must be 1:1");
// Save the prices
for (uint i = 0; i < messages.length; i++) {
priceData.put(messages[i], signatures[i]);
}
uint ethPrice = fetchEthPrice();
// Try to update the view storage
for (uint i = 0; i < symbols.length; i++) {
postPriceInternal(symbols[i], ethPrice);
}
}
function postPriceInternal(string memory symbol, uint ethPrice) internal {
TokenConfig memory config = getTokenConfigBySymbol(symbol);
require(config.priceSource == PriceSource.REPORTER, "only reporter prices get posted");
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
uint reporterPrice = priceData.getPrice(reporter, symbol);
uint anchorPrice;
if (symbolHash == ethHash) {
anchorPrice = ethPrice;
} else {
anchorPrice = fetchAnchorPrice(symbol, config, ethPrice);
}
if (reporterInvalidated) {
prices[symbolHash] = anchorPrice;
emit PriceUpdated(symbol, anchorPrice);
} else if (isWithinAnchor(reporterPrice, anchorPrice)) {
prices[symbolHash] = reporterPrice;
emit PriceUpdated(symbol, reporterPrice);
} else {
emit PriceGuarded(symbol, reporterPrice, anchorPrice);
}
}
function isWithinAnchor(uint reporterPrice, uint anchorPrice) internal view returns (bool) {
if (reporterPrice > 0) {
uint anchorRatio = mul(anchorPrice, 100e16) / reporterPrice;
return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
}
return false;
}
/**
* @dev Fetches the current token/eth price accumulator from uniswap.
*/
function currentCumulativePrice(TokenConfig memory config) internal view returns (uint) {
(uint cumulativePrice0, uint cumulativePrice1,) = UniswapV2OracleLibrary.currentCumulativePrices(config.uniswapMarket);
if (config.isUniswapReversed) {
return cumulativePrice1;
} else {
return cumulativePrice0;
}
}
/**
* @dev Fetches the current eth/usd price from uniswap, with 6 decimals of precision.
* Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals.
*/
function fetchEthPrice() internal returns (uint) {
return fetchAnchorPrice("ETH", getTokenConfigBySymbolHash(ethHash), ethBaseUnit);
}
/**
* @dev Fetches the current token/usd price from uniswap, with 6 decimals of precision.
* @param conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets
*/
function fetchAnchorPrice(string memory symbol, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) {
(uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config);
// This should be impossible, but better safe than sorry
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
// Calculate uniswap time-weighted average price
// Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed));
uint rawUniswapPriceMantissa = priceAverage.decode112with18();
uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor);
uint anchorPrice;
// Adjust rawUniswapPrice according to the units of the non-ETH asset
// In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels
if (config.isUniswapReversed) {
// unscaledPriceMantissa * ethBaseUnit / config.baseUnit / expScale, but we simplify bc ethBaseUnit == expScale
anchorPrice = unscaledPriceMantissa / config.baseUnit;
} else {
anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale;
}
emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp);
return anchorPrice;
}
/**
* @dev Get time-weighted average prices for a token at the current timestamp.
* Update new and old observations of lagging window if period elapsed.
*/
function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) {
bytes32 symbolHash = config.symbolHash;
uint cumulativePrice = currentCumulativePrice(config);
Observation memory newObservation = newObservations[symbolHash];
// Update new and old observations if elapsed time is greater than or equal to anchor period
uint timeElapsed = block.timestamp - newObservation.timestamp;
if (timeElapsed >= anchorPeriod) {
oldObservations[symbolHash].timestamp = newObservation.timestamp;
oldObservations[symbolHash].acc = newObservation.acc;
newObservations[symbolHash].timestamp = block.timestamp;
newObservations[symbolHash].acc = cumulativePrice;
emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice);
}
return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp);
}
/**
* @notice Invalidate the reporter, and fall back to using anchor directly in all cases
* @dev Only the reporter may sign a message which allows it to invalidate itself.
* To be used in cases of emergency, if the reporter thinks their key may be compromised.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
*/
function invalidateReporter(bytes memory message, bytes memory signature) external {
(string memory decodedMessage, ) = abi.decode(message, (string, address));
require(keccak256(abi.encodePacked(decodedMessage)) == rotateHash, "invalid message must be 'rotate'");
require(source(message, signature) == reporter, "invalidation message must come from the reporter");
reporterInvalidated = true;
emit ReporterInvalidated(reporter);
}
/**
* @notice Recovers the source address which signed a message
* @dev Comparing to a claimed address would add nothing,
* as the caller could simply perform the recover and claim that address.
* @param message The data that was presumably signed
* @param signature The fingerprint of the data + private key
* @return The source address which signed the message, presumably
*/
function source(bytes memory message, bytes memory signature) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message)));
return ecrecover(hash, v, r, s);
}
/// @dev Overflow proof multiplication
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint c = a * b;
require(c / a == b, "multiplication overflow");
return c;
}
} | * @title The Open Oracle Data Base Contract @author Compound Labs, Inc./event Write(address indexed source, <Key> indexed key, string kind, uint64 timestamp, <Value> value);function put(bytes calldata message, bytes calldata signature) external returns (<Key> memory);function get(address source, <Key> key) external view returns (uint, <Value>); | contract OpenOracleData {
function source(bytes memory message, bytes memory signature) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message)));
return ecrecover(hash, v, r, s);
}
}
| 6,497,057 | [
1,
1986,
3502,
28544,
1910,
3360,
13456,
225,
21327,
511,
5113,
16,
15090,
18,
19,
2575,
2598,
12,
2867,
8808,
1084,
16,
411,
653,
34,
8808,
498,
16,
533,
3846,
16,
2254,
1105,
2858,
16,
411,
620,
34,
460,
1769,
915,
1378,
12,
3890,
745,
892,
883,
16,
1731,
745,
892,
3372,
13,
3903,
1135,
261,
32,
653,
34,
3778,
1769,
915,
336,
12,
2867,
1084,
16,
411,
653,
34,
498,
13,
3903,
1476,
1135,
261,
11890,
16,
411,
620,
34,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3502,
23601,
751,
288,
203,
203,
203,
203,
203,
203,
203,
565,
445,
1084,
12,
3890,
3778,
883,
16,
1731,
3778,
3372,
13,
1071,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
261,
3890,
1578,
436,
16,
1731,
1578,
272,
16,
2254,
28,
331,
13,
273,
24126,
18,
3922,
12,
8195,
16,
261,
3890,
1578,
16,
1731,
1578,
16,
2254,
28,
10019,
203,
3639,
1731,
1578,
1651,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
417,
24410,
581,
5034,
12,
2150,
3719,
1769,
203,
3639,
327,
425,
1793,
3165,
12,
2816,
16,
331,
16,
436,
16,
272,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
//
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ----------------------------------------------------------------------------
contract CELT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "CELT";
name = "COSS Exchange Liquidity Token";
decimals = 18;
_totalSupply = 10000000 ether;
balances[owner] = _totalSupply;
emit Transfer(address(0),owner, _totalSupply);
Hub_.setAuto(10);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) updateAccount(to) updateAccount(msg.sender) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens)updateAccount(to) updateAccount(from) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// Hub_
PlincInterface constant Hub_ = PlincInterface(0xd5D10172e8D8B84AC83031c16fE093cba4c84FC6);
uint256 public ethPendingDistribution;
// plinc functions
function fetchHubVault() public{
uint256 value = Hub_.playerVault(address(this));
require(value >0);
Hub_.vaultToWallet();
ethPendingDistribution = ethPendingDistribution.add(value);
}
function fetchHubPiggy() public{
uint256 value = Hub_.piggyBank(address(this));
require(value >0);
Hub_.piggyToWallet();
ethPendingDistribution = ethPendingDistribution.add(value);
}
function disburseHub() public {
uint256 amount = ethPendingDistribution;
ethPendingDistribution = 0;
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
// PSAfunctions
// PSAsection
uint256 public pointMultiplier = 10e18;
struct Account {
uint balance;
uint lastDividendPoints;
}
mapping(address=>Account) accounts;
mapping(address=>uint256) public PSA;
uint public ethtotalSupply;
uint public totalDividendPoints;
uint public unclaimedDividends;
function dividendsOwing(address account) public view returns(uint256) {
uint256 newDividendPoints = totalDividendPoints.sub(accounts[account].lastDividendPoints);
return (balances[account] * newDividendPoints) / pointMultiplier;
}
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if(owing > 0) {
unclaimedDividends = unclaimedDividends.sub(owing);
PSA[account] = PSA[account].add(owing);
}
accounts[account].lastDividendPoints = totalDividendPoints;
_;
}
// payable fallback to receive eth
function () external payable{}
// fetch PSA allocation to personal mapping
function fetchPSA() public updateAccount(msg.sender){}
// Give out PSA to CELT holders
function disburse() public payable {
uint256 base = msg.value.div(20);
uint256 amount = msg.value.sub(base);
Hub_.buyBonds.value(base)(address(this)) ;
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
function PSAtoWallet() public {
if(dividendsOwing(msg.sender) > 0)
{
fetchPSA();
}
uint256 amount = PSA[msg.sender];
require(amount >0);
PSA[msg.sender] = 0;
msg.sender.transfer(amount) ;
}
function PSAtoWalletByAddres(address toAllocate) public {
uint256 amount = PSA[toAllocate];
require(amount >0);
PSA[toAllocate] = 0;
toAllocate.transfer(amount) ;
}
function rectifyWrongs(address toAllocate, uint256 amount) public onlyOwner {
require(amount >0);
toAllocate.transfer(amount) ;
}
}
interface PlincInterface {
function IdToAdress(uint256 index) external view returns(address);
function nextPlayerID() external view returns(uint256);
function bondsOutstanding(address player) external view returns(uint256);
function playerVault(address player) external view returns(uint256);
function piggyBank(address player) external view returns(uint256);
function vaultToWallet() external ;
function piggyToWallet() external ;
function setAuto (uint256 percentage)external ;
function buyBonds( address referral)external payable ;
} | Give out PSA to CELT holders | function disburse() public payable {
uint256 base = msg.value.div(20);
uint256 amount = msg.value.sub(base);
Hub_.buyBonds.value(base)(address(this)) ;
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
| 2,553,669 | [
1,
43,
688,
596,
453,
5233,
358,
385,
2247,
56,
366,
4665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1015,
70,
295,
307,
1435,
1071,
225,
8843,
429,
288,
203,
3639,
2254,
5034,
1026,
273,
1234,
18,
1132,
18,
2892,
12,
3462,
1769,
203,
3639,
2254,
5034,
3844,
273,
1234,
18,
1132,
18,
1717,
12,
1969,
1769,
203,
3639,
21353,
27799,
70,
9835,
26090,
18,
1132,
12,
1969,
21433,
2867,
12,
2211,
3719,
274,
203,
3639,
2078,
7244,
26746,
5636,
273,
2078,
7244,
26746,
5636,
18,
1289,
12,
8949,
18,
16411,
12,
1153,
23365,
2934,
2892,
24899,
4963,
3088,
1283,
10019,
203,
3639,
6301,
80,
4581,
329,
7244,
350,
5839,
273,
6301,
80,
4581,
329,
7244,
350,
5839,
18,
1289,
12,
8949,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @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 ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface Migratable {
function migrateTo(address user, address token, uint256 amount) payable external;
}
/*
* @title Solidity Bytes Arrays Utils
* @author GonΓ§alo SΓ‘ <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
/**
* @title Serializable Migration
* @author Ben Huang
* @notice Let migration support serialization and deserialization
*/
contract SerializableMigration {
using SafeMath for uint256;
using BytesLib for bytes;
uint constant public MIGRATION_1_SIZE = 24;
uint constant public TOKENID_SIZE = 2;
uint constant public SIGNATURE_SIZE = 65;
uint8 constant internal _MASK_IS_ETH = 0x01;
/**
* @notice Get target address from the serialized migration data
* @param ser_data Serialized migration data
* @return target Target contract address
*/
function _getMigrationTarget(bytes memory ser_data) internal pure returns (address target) {
target = ser_data.toAddress(ser_data.length - 20);
}
/**
* @notice Get user ID from the serialized migration data
* @param ser_data Serialized migration data
* @return userID User ID
*/
function _getMigrationUserID(bytes memory ser_data) internal pure returns (uint256 userID) {
userID = ser_data.toUint32(ser_data.length - 24);
}
/**
* @notice Get token count
* @param ser_data Serialized migration data
* @return n The migrate token amount
*/
function _getMigrationCount(bytes memory ser_data) internal pure returns (uint256 n) {
n = (ser_data.length - SIGNATURE_SIZE - MIGRATION_1_SIZE) / 2;
}
/**
* @notice Get token ID to be migrated
* @param ser_data Serialized migration data
* @param index The index of token ID to be migrated
* @return tokenID The token ID to be migrated
*/
function _getMigrationTokenID(bytes memory ser_data, uint index) internal pure returns (uint256 tokenID) {
require(index < _getMigrationCount(ser_data));
tokenID = ser_data.toUint16(ser_data.length - MIGRATION_1_SIZE - (TOKENID_SIZE.mul(index + 1)));
}
/**
* @notice Get v from the serialized migration data
* @param ser_data Serialized migration data
* @return v Signature v
*/
function _getMigrationV(bytes memory ser_data) internal pure returns (uint8 v) {
v = ser_data.toUint8(SIGNATURE_SIZE - 1);
}
/**
* @notice Get r from the serialized migration data
* @param ser_data Serialized migration data
* @return r Signature r
*/
function _getMigrationR(bytes memory ser_data) internal pure returns (bytes32 r) {
r = ser_data.toBytes32(SIGNATURE_SIZE - 33);
}
/**
* @notice Get s from the serialized migration data
* @param ser_data Serialized migration data
* @return s Signature s
*/
function _getMigrationS(bytes memory ser_data) internal pure returns (bytes32 s) {
s = ser_data.toBytes32(SIGNATURE_SIZE - 65);
}
/**
* @notice Get hash from the serialized migration data
* @param ser_data Serialized migration data
* @return hash Migration hash without signature
*/
function _getMigrationHash(bytes memory ser_data) internal pure returns (bytes32 hash) {
hash = keccak256(ser_data.slice(65, ser_data.length - SIGNATURE_SIZE));
}
}
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n Γ· 2 + 1, and for v in (282): v β {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
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));
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
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);
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 equal true).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
/**
* @title Serializable Order
* @author Ben Huang
* @notice Let order support serialization and deserialization
*/
contract SerializableOrder {
using SafeMath for uint256;
using BytesLib for bytes;
uint constant public ORDER_SIZE = 206;
uint constant public UNSIGNED_ORDER_SIZE = 141;
uint8 constant internal _MASK_IS_BUY = 0x01;
uint8 constant internal _MASK_IS_MAIN = 0x02;
/**
* @notice Get user ID from the serialized order data
* @param ser_data Serialized order data
* @return userID User ID
*/
function _getOrderUserID(bytes memory ser_data) internal pure returns (uint256 userID) {
userID = ser_data.toUint32(ORDER_SIZE - 4);
}
/**
* @notice Get base token ID from the serialized order data
* @param ser_data Serialized order data
* @return tokenBase Base token ID
*/
function _getOrderTokenIDBase(bytes memory ser_data) internal pure returns (uint256 tokenBase) {
tokenBase = ser_data.toUint16(ORDER_SIZE - 6);
}
/**
* @notice Get base token amount from the serialized order data
* @param ser_data Serialized order data
* @return amountBase Base token amount
*/
function _getOrderAmountBase(bytes memory ser_data) internal pure returns (uint256 amountBase) {
amountBase = ser_data.toUint(ORDER_SIZE - 38);
}
/**
* @notice Get quote token ID from the serialized order data
* @param ser_data Serialized order data
* @return tokenQuote Quote token ID
*/
function _getOrderTokenIDQuote(bytes memory ser_data) internal pure returns (uint256 tokenQuote) {
tokenQuote = ser_data.toUint16(ORDER_SIZE - 40);
}
/**
* @notice Get quote token amount from the serialized order data
* @param ser_data Serialized order data
* @return amountQuote Quote token amount
*/
function _getOrderAmountQuote(bytes memory ser_data) internal pure returns (uint256 amountQuote) {
amountQuote = ser_data.toUint(ORDER_SIZE - 72);
}
/**
* @notice Check if the order is a buy order
* @param ser_data Serialized order data
* @return fBuy Is buy order or not
*/
function _isOrderBuy(bytes memory ser_data) internal pure returns (bool fBuy) {
fBuy = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_BUY != 0);
}
/**
* @notice Check if the fee is paid by main token
* @param ser_data Serialized order data
* @return fMain Is the fee paid in main token or not
*/
function _isOrderFeeMain(bytes memory ser_data) internal pure returns (bool fMain) {
fMain = (ser_data.toUint8(ORDER_SIZE - 73) & _MASK_IS_MAIN != 0);
}
/**
* @notice Get nonce from the serialized order data
* @param ser_data Serialized order data
* @return nonce Nonce
*/
function _getOrderNonce(bytes memory ser_data) internal pure returns (uint256 nonce) {
nonce = ser_data.toUint32(ORDER_SIZE - 77);
}
/**
* @notice Get trading fee from the serialized order data
* @param ser_data Serialized order data
* @return fee Fee amount
*/
function _getOrderTradeFee(bytes memory ser_data) internal pure returns (uint256 tradeFee) {
tradeFee = ser_data.toUint(ORDER_SIZE - 109);
}
/**
* @notice Get gas fee from the serialized order data
* @param ser_data Serialized order data
* @return fee Fee amount
*/
function _getOrderGasFee(bytes memory ser_data) internal pure returns (uint256 gasFee) {
gasFee = ser_data.toUint(ORDER_SIZE - 141);
}
/**
* @notice Get v from the serialized order data
* @param ser_data Serialized order data
* @return v Signature v
*/
function _getOrderV(bytes memory ser_data) internal pure returns (uint8 v) {
v = ser_data.toUint8(ORDER_SIZE - 142);
}
/**
* @notice Get r from the serialized order data
* @param ser_data Serialized order data
* @return r Signature r
*/
function _getOrderR(bytes memory ser_data) internal pure returns (bytes32 r) {
r = ser_data.toBytes32(ORDER_SIZE - 174);
}
/**
* @notice Get s from the serialized order data
* @param ser_data Serialized order data
* @return s Signature s
*/
function _getOrderS(bytes memory ser_data) internal pure returns (bytes32 s) {
s = ser_data.toBytes32(ORDER_SIZE - 206);
}
/**
* @notice Get hash from the serialized order data
* @param ser_data Serialized order data
* @return hash Order hash without signature
*/
function _getOrderHash(bytes memory ser_data) internal pure returns (bytes32 hash) {
hash = keccak256(ser_data.slice(65, UNSIGNED_ORDER_SIZE));
}
/**
* @notice Fetch the serialized order data with the given index
* @param ser_data Serialized order data
* @param index The index of order to be fetched
* @return order_data The fetched order data
*/
function _getOrder(bytes memory ser_data, uint index) internal pure returns (bytes memory order_data) {
require(index < _getOrderCount(ser_data));
order_data = ser_data.slice(ORDER_SIZE.mul(index), ORDER_SIZE);
}
/**
* @notice Count the order amount
* @param ser_data Serialized order data
* @return amount Order amount
*/
function _getOrderCount(bytes memory ser_data) internal pure returns (uint256 amount) {
amount = ser_data.length.div(ORDER_SIZE);
}
}
/**
* @title Serializable Withdrawal
* @author Ben Huang
* @notice Let withdrawal support serialization and deserialization
*/
contract SerializableWithdrawal {
using SafeMath for uint256;
using BytesLib for bytes;
uint constant public WITHDRAWAL_SIZE = 140;
uint constant public UNSIGNED_WITHDRAWAL_SIZE = 75;
uint8 constant internal _MASK_IS_ETH = 0x01;
/**
* @notice Get user ID from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return userID User ID
*/
function _getWithdrawalUserID(bytes memory ser_data) internal pure returns (uint256 userID) {
userID = ser_data.toUint32(WITHDRAWAL_SIZE - 4);
}
/**
* @notice Get token ID from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return tokenID Withdrawal token ID
*/
function _getWithdrawalTokenID(bytes memory ser_data) internal pure returns (uint256 tokenID) {
tokenID = ser_data.toUint16(WITHDRAWAL_SIZE - 6);
}
/**
* @notice Get amount from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return amount Withdrawal token amount
*/
function _getWithdrawalAmount(bytes memory ser_data) internal pure returns (uint256 amount) {
amount = ser_data.toUint(WITHDRAWAL_SIZE - 38);
}
/**
* @notice Check if the fee is paid by main token
* @param ser_data Serialized withdrawal data
* @return fETH Is the fee paid in ETH or DGO
*/
function _isWithdrawalFeeETH(bytes memory ser_data) internal pure returns (bool fFeeETH) {
fFeeETH = (ser_data.toUint8(WITHDRAWAL_SIZE - 39) & _MASK_IS_ETH != 0);
}
/**
* @notice Get nonce from the serialized withrawal data
* @param ser_data Serialized withdrawal data
* @return nonce Nonce
*/
function _getWithdrawalNonce(bytes memory ser_data) internal pure returns (uint256 nonce) {
nonce = ser_data.toUint32(WITHDRAWAL_SIZE - 43);
}
/**
* @notice Get fee amount from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return fee Fee amount
*/
function _getWithdrawalFee(bytes memory ser_data) internal pure returns (uint256 fee) {
fee = ser_data.toUint(WITHDRAWAL_SIZE - 75);
}
/**
* @notice Get v from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return v Signature v
*/
function _getWithdrawalV(bytes memory ser_data) internal pure returns (uint8 v) {
v = ser_data.toUint8(WITHDRAWAL_SIZE - 76);
}
/**
* @notice Get r from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return r Signature r
*/
function _getWithdrawalR(bytes memory ser_data) internal pure returns (bytes32 r) {
r = ser_data.toBytes32(WITHDRAWAL_SIZE - 108);
}
/**
* @notice Get s from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return s Signature s
*/
function _getWithdrawalS(bytes memory ser_data) internal pure returns (bytes32 s) {
s = ser_data.toBytes32(WITHDRAWAL_SIZE - 140);
}
/**
* @notice Get hash from the serialized withdrawal data
* @param ser_data Serialized withdrawal data
* @return hash Withdrawal hash without signature
*/
function _getWithdrawalHash(bytes memory ser_data) internal pure returns (bytes32 hash) {
hash = keccak256(ser_data.slice(65, UNSIGNED_WITHDRAWAL_SIZE));
}
}
/**
* @title Dinngo
* @author Ben Huang
* @notice Main exchange contract for Dinngo
*/
contract Dinngo is SerializableOrder, SerializableWithdrawal, SerializableMigration {
// Storage alignment
address private _owner;
mapping (address => bool) private admins;
uint256 private _nAdmin;
uint256 private _nLimit;
// end
using ECDSA for bytes32;
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public processTime;
mapping (address => mapping (address => uint256)) public balances;
mapping (bytes32 => uint256) public orderFills;
mapping (uint256 => address payable) public userID_Address;
mapping (uint256 => address) public tokenID_Address;
mapping (address => uint256) public userRanks;
mapping (address => uint256) public tokenRanks;
mapping (address => uint256) public lockTimes;
event AddUser(uint256 userID, address indexed user);
event AddToken(uint256 tokenID, address indexed token);
event Deposit(address token, address indexed user, uint256 amount, uint256 balance);
event Withdraw(
address token,
address indexed user,
uint256 amount,
uint256 balance,
address tokenFee,
uint256 amountFee
);
event Trade(
address indexed user,
bool isBuy,
address indexed tokenBase,
uint256 amountBase,
address indexed tokenQuote,
uint256 amountQuote,
address tokenFee,
uint256 amountFee
);
event Lock(address indexed user, uint256 lockTime);
event Unlock(address indexed user);
/**
* @dev All ether directly sent to contract will be refunded
*/
function() external payable {
revert();
}
/**
* @notice Add the address to the user list. Event AddUser will be emitted
* after execution.
* @dev Record the user list to map the user address to a specific user ID, in
* order to compact the data size when transferring user address information
* @dev id should be less than 2**32
* @param id The user id to be assigned
* @param user The user address to be added
*/
function addUser(uint256 id, address payable user) external {
require(user != address(0));
require(userRanks[user] == 0);
require(id < 2**32);
if (userID_Address[id] == address(0))
userID_Address[id] = user;
else
require(userID_Address[id] == user);
userRanks[user] = 1;
emit AddUser(id, user);
}
/**
* @notice Remove the address from the user list.
* @dev The user rank is set to 0 to remove the user.
* @param user The user address to be added
*/
function removeUser(address user) external {
require(user != address(0));
require(userRanks[user] != 0);
userRanks[user] = 0;
}
/**
* @notice Update the rank of user. Can only be called by owner.
* @param user The user address
* @param rank The rank to be assigned
*/
function updateUserRank(address user, uint256 rank) external {
require(user != address(0));
require(rank != 0);
require(userRanks[user] != 0);
require(userRanks[user] != rank);
userRanks[user] = rank;
}
/**
* @notice Add the token to the token list. Event AddToken will be emitted
* after execution.
* @dev Record the token list to map the token contract address to a specific
* token ID, in order to compact the data size when transferring token contract
* address information
* @dev id should be less than 2**16
* @param id The token id to be assigned
* @param token The token contract address to be added
*/
function addToken(uint256 id, address token) external {
require(token != address(0));
require(tokenRanks[token] == 0);
require(id < 2**16);
if (tokenID_Address[id] == address(0))
tokenID_Address[id] = token;
else
require(tokenID_Address[id] == token);
tokenRanks[token] = 1;
emit AddToken(id, token);
}
/**
* @notice Remove the token to the token list.
* @dev The token rank is set to 0 to remove the token.
* @param token The token contract address to be removed.
*/
function removeToken(address token) external {
require(token != address(0));
require(tokenRanks[token] != 0);
tokenRanks[token] = 0;
}
/**
* @notice Update the rank of token. Can only be called by owner.
* @param token The token contract address.
* @param rank The rank to be assigned.
*/
function updateTokenRank(address token, uint256 rank) external {
require(token != address(0));
require(rank != 0);
require(tokenRanks[token] != 0);
require(tokenRanks[token] != rank);
tokenRanks[token] = rank;
}
/**
* @notice The deposit function for ether. The ether that is sent with the function
* call will be deposited. The first time user will be added to the user list.
* Event Deposit will be emitted after execution.
*/
function deposit() external payable {
require(!_isLocking(msg.sender));
require(msg.value > 0);
balances[address(0)][msg.sender] = balances[address(0)][msg.sender].add(msg.value);
emit Deposit(address(0), msg.sender, msg.value, balances[address(0)][msg.sender]);
}
/**
* @notice The deposit function for tokens. The first time user will be added to
* the user list. Event Deposit will be emitted after execution.
* @param token Address of the token contract to be deposited
* @param amount Amount of the token to be depositied
*/
function depositToken(address token, uint256 amount) external {
require(token != address(0));
require(!_isLocking(msg.sender));
require(_isValidToken(token));
require(amount > 0);
balances[token][msg.sender] = balances[token][msg.sender].add(amount);
emit Deposit(token, msg.sender, amount, balances[token][msg.sender]);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice The withdraw function for ether. Event Withdraw will be emitted
* after execution. User needs to be locked before calling withdraw.
* @param amount The amount to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(_isLocked(msg.sender));
require(_isValidUser(msg.sender));
require(amount > 0);
balances[address(0)][msg.sender] = balances[address(0)][msg.sender].sub(amount);
emit Withdraw(address(0), msg.sender, amount, balances[address(0)][msg.sender], address(0), 0);
msg.sender.transfer(amount);
}
/**
* @notice The withdraw function for tokens. Event Withdraw will be emitted
* after execution. User needs to be locked before calling withdraw.
* @param token The token contract address to be withdrawn.
* @param amount The token amount to be withdrawn.
*/
function withdrawToken(address token, uint256 amount) external {
require(token != address(0));
require(_isLocked(msg.sender));
require(_isValidUser(msg.sender));
require(_isValidToken(token));
require(amount > 0);
balances[token][msg.sender] = balances[token][msg.sender].sub(amount);
emit Withdraw(token, msg.sender, amount, balances[token][msg.sender], address(0), 0);
IERC20(token).safeTransfer(msg.sender, amount);
}
/**
* @notice The withdraw function that can only be triggered by owner.
* Event Withdraw will be emitted after execution.
* @param withdrawal The serialized withdrawal data
*/
function withdrawByAdmin(bytes calldata withdrawal) external {
address payable user = userID_Address[_getWithdrawalUserID(withdrawal)];
address wallet = userID_Address[0];
address token = tokenID_Address[_getWithdrawalTokenID(withdrawal)];
uint256 amount = _getWithdrawalAmount(withdrawal);
uint256 amountFee = _getWithdrawalFee(withdrawal);
address tokenFee = _isWithdrawalFeeETH(withdrawal)? address(0) : tokenID_Address[1];
uint256 balance = balances[token][user].sub(amount);
require(_isValidUser(user));
_verifySig(
user,
_getWithdrawalHash(withdrawal),
_getWithdrawalR(withdrawal),
_getWithdrawalS(withdrawal),
_getWithdrawalV(withdrawal)
);
if (tokenFee == token) {
balance = balance.sub(amountFee);
} else {
balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee);
}
balances[tokenFee][wallet] =
balances[tokenFee][wallet].add(amountFee);
balances[token][user] = balance;
emit Withdraw(token, user, amount, balance, tokenFee, amountFee);
if (token == address(0)) {
user.transfer(amount);
} else {
IERC20(token).safeTransfer(user, amount);
}
}
/**
* @notice The migrate function the can only triggered by admin.
* Event Migrate will be emitted after execution.
* @param migration The serialized migration data
*/
function migrateByAdmin(bytes calldata migration) external {
address target = _getMigrationTarget(migration);
address user = userID_Address[_getMigrationUserID(migration)];
uint256 nToken = _getMigrationCount(migration);
require(_isValidUser(user));
_verifySig(
user,
_getMigrationHash(migration),
_getMigrationR(migration),
_getMigrationS(migration),
_getMigrationV(migration)
);
for (uint i = 0; i < nToken; i++) {
address token = tokenID_Address[_getMigrationTokenID(migration, i)];
uint256 balance = balances[token][user];
require(balance != 0);
balances[token][user] = 0;
if (token == address(0)) {
Migratable(target).migrateTo.value(balance)(user, token, balance);
} else {
IERC20(token).approve(target, balance);
Migratable(target).migrateTo(user, token, balance);
}
}
}
/**
* @notice The settle function for orders. First order is taker order and the followings
* are maker orders.
* @param orders The serialized orders.
*/
function settle(bytes calldata orders) external {
// Deal with the order list
uint256 nOrder = _getOrderCount(orders);
// Get the first order as the taker order
bytes memory takerOrder = _getOrder(orders, 0);
uint256 totalAmountBase = _getOrderAmountBase(takerOrder);
uint256 takerAmountBase = totalAmountBase.sub(orderFills[_getOrderHash(takerOrder)]);
uint256 fillAmountQuote = 0;
uint256 restAmountBase = takerAmountBase;
bool fBuy = _isOrderBuy(takerOrder);
// Parse maker orders
for (uint i = 1; i < nOrder; i++) {
// Get ith order as the maker order
bytes memory makerOrder = _getOrder(orders, i);
require(fBuy != _isOrderBuy(makerOrder));
uint256 makerAmountBase = _getOrderAmountBase(makerOrder);
// Calculate the amount to be executed
uint256 amountBase = makerAmountBase.sub(orderFills[_getOrderHash(makerOrder)]);
amountBase = amountBase <= restAmountBase? amountBase : restAmountBase;
uint256 amountQuote = _getOrderAmountQuote(makerOrder).mul(amountBase).div(makerAmountBase);
restAmountBase = restAmountBase.sub(amountBase);
fillAmountQuote = fillAmountQuote.add(amountQuote);
// Trade amountBase and amountQuote for maker order
_trade(amountBase, amountQuote, makerOrder);
}
// Sum the trade amount and check
takerAmountBase = takerAmountBase.sub(restAmountBase);
if (fBuy) {
require(fillAmountQuote.mul(totalAmountBase)
<= _getOrderAmountQuote(takerOrder).mul(takerAmountBase));
} else {
require(fillAmountQuote.mul(totalAmountBase)
>= _getOrderAmountQuote(takerOrder).mul(takerAmountBase));
}
// Trade amountBase and amountQuote for taker order
_trade(takerAmountBase, fillAmountQuote, takerOrder);
}
/**
* @notice Announce lock of the sender
*/
function lock() external {
require(!_isLocking(msg.sender));
lockTimes[msg.sender] = now.add(processTime);
emit Lock(msg.sender, lockTimes[msg.sender]);
}
/**
* @notice Unlock the sender
*/
function unlock() external {
require(_isLocking(msg.sender));
lockTimes[msg.sender] = 0;
emit Unlock(msg.sender);
}
/**
* @notice Change the processing time of locking the user address
*/
function changeProcessTime(uint256 time) external {
require(processTime != time);
processTime = time;
}
/**
* @notice Process the trade by the providing information
* @param amountBase The provided amount to be traded
* @param amountQuote The amount to be requested
* @param order The order that triggered the trading
*/
function _trade(uint256 amountBase, uint256 amountQuote, bytes memory order) internal {
require(amountBase != 0);
// Get parameters
address user = userID_Address[_getOrderUserID(order)];
address wallet = userID_Address[0];
bytes32 hash = _getOrderHash(order);
address tokenQuote = tokenID_Address[_getOrderTokenIDQuote(order)];
address tokenBase = tokenID_Address[_getOrderTokenIDBase(order)];
address tokenFee;
uint256 amountFee =
_getOrderTradeFee(order).mul(amountBase).div(_getOrderAmountBase(order));
require(_isValidUser(user));
// Trade and fee setting
if (orderFills[hash] == 0) {
_verifySig(user, hash, _getOrderR(order), _getOrderS(order), _getOrderV(order));
amountFee = amountFee.add(_getOrderGasFee(order));
}
bool fBuy = _isOrderBuy(order);
if (fBuy) {
balances[tokenQuote][user] = balances[tokenQuote][user].sub(amountQuote);
if (_isOrderFeeMain(order)) {
tokenFee = tokenBase;
balances[tokenBase][user] = balances[tokenBase][user].add(amountBase).sub(amountFee);
balances[tokenBase][wallet] = balances[tokenBase][wallet].add(amountFee);
} else {
tokenFee = tokenID_Address[1];
balances[tokenBase][user] = balances[tokenBase][user].add(amountBase);
balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee);
balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee);
}
} else {
balances[tokenBase][user] = balances[tokenBase][user].sub(amountBase);
if (_isOrderFeeMain(order)) {
tokenFee = tokenQuote;
balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote).sub(amountFee);
balances[tokenQuote][wallet] = balances[tokenQuote][wallet].add(amountFee);
} else {
tokenFee = tokenID_Address[1];
balances[tokenQuote][user] = balances[tokenQuote][user].add(amountQuote);
balances[tokenFee][user] = balances[tokenFee][user].sub(amountFee);
balances[tokenFee][wallet] = balances[tokenFee][wallet].add(amountFee);
}
}
// Order fill
orderFills[hash] = orderFills[hash].add(amountBase);
emit Trade
(
user,
fBuy,
tokenBase,
amountBase,
tokenQuote,
amountQuote,
tokenFee,
amountFee
);
}
/**
* @dev Check if the user is valid
* @param user The user address to be checked.
*/
function _isValidUser(address user) internal view returns (bool) {
return userRanks[user] != 0;
}
/**
* @dev Check if the token is valid
* @param token The token address to be checked.
*/
function _isValidToken(address token) internal view returns (bool) {
return tokenRanks[token] != 0;
}
/**
* @notice Verify if the data is signed by the given user and signature
* @param user The signing user
* @param hash The data hash to be verified
* @param r The signature R
* @param s The signature S
* @param v The signature V
*/
function _verifySig(address user, bytes32 hash, bytes32 r, bytes32 s, uint8 v) internal pure {
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
address sigAddr = ecrecover(hash.toEthSignedMessageHash(), v, r, s);
require(user == sigAddr);
}
/**
* @notice Return if the give user has announced lock
* @param user The user address to be queried
* @return Query result
*/
function _isLocking(address user) internal view returns (bool) {
return lockTimes[user] > 0;
}
/**
* @notice Return if the user is locked
* @param user The user address to be queried
*/
function _isLocked(address user) internal view returns (bool) {
return _isLocking(user) && lockTimes[user] < now;
}
} | * @notice Remove the address from the user list. @dev The user rank is set to 0 to remove the user. @param user The user address to be added/ | function removeUser(address user) external {
require(user != address(0));
require(userRanks[user] != 0);
userRanks[user] = 0;
}
| 15,834,856 | [
1,
3288,
326,
1758,
628,
326,
729,
666,
18,
225,
1021,
729,
6171,
353,
444,
358,
374,
358,
1206,
326,
729,
18,
225,
729,
1021,
729,
1758,
358,
506,
3096,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
1299,
12,
2867,
729,
13,
3903,
288,
203,
3639,
2583,
12,
1355,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
1355,
12925,
87,
63,
1355,
65,
480,
374,
1769,
203,
3639,
729,
12925,
87,
63,
1355,
65,
273,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
contract theCyberInterface {
// The contract may call a few methods on theCyber once it is itself a member.
function newMember(uint8 _memberId, bytes32 _memberName, address _memberAddress) public;
function getMembershipStatus(address _memberAddress) public view returns (bool member, uint8 memberId);
function getMemberInformation(uint8 _memberId) public view returns (bytes32 memberName, string memberKey, uint64 memberSince, uint64 inactiveSince, address memberAddress);
}
contract theCyberGatekeeperTwoInterface {
// The contract may read the entrants from theCyberGatekeeperTwo.
function entrants(uint256 i) public view returns (address);
function totalEntrants() public view returns (uint8);
}
contract theCyberAssigner {
// This contract supplements the second gatekeeper contract at the address
// 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C. Once enough members have been
// registered with the gatekeeper, the assignAll() method may be called,
// which (assuming theCyberAssigner is itself a member of theCyber), will
// try to assign a membership to each of the submitted addresses.
// The assigner will interact with theCyber contract at the given address.
address private constant THECYBERADDRESS_ = 0x97A99C819544AD0617F48379840941eFbe1bfAE1;
// the assigner will read the entrants from the second gatekeeper contract.
address private constant THECYBERGATEKEEPERADDRESS_ = 0xbB902569a997D657e8D10B82Ce0ec5A5983C8c7C;
// There can only be 128 entrant submissions.
uint8 private constant MAXENTRANTS_ = 128;
// The contract remains active until all entrants have been assigned.
bool private active_ = true;
// Entrants are assigned memberships based on an incrementing member id.
uint8 private nextAssigneeIndex_;
function assignAll() public returns (bool) {
// The contract must still be active in order to assign new members.
require(active_);
// Require a large transaction so that members are added in bulk.
require(msg.gas > 6000000);
// All entrants must be registered in order to assign new members.
uint8 totalEntrants = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).totalEntrants();
require(totalEntrants >= MAXENTRANTS_);
// Initialize variables for checking membership statuses.
bool member;
address memberAddress;
// The contract must be a member of theCyber in order to assign new members.
(member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(this);
require(member);
// Pick up where the function last left off in assigning new members.
uint8 i = nextAssigneeIndex_;
// Loop through entrants as long as sufficient gas remains.
while (i < MAXENTRANTS_ && msg.gas > 200000) {
// Find the entrant at the given index.
address entrant = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).entrants(i);
// Determine whether the entrant is already a member of theCyber.
(member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(entrant);
// Determine whether the target membership is already owned.
(,,,,memberAddress) = theCyberInterface(THECYBERADDRESS_).getMemberInformation(i + 1);
// Ensure that there was no member found with the given id / address.
if ((entrant != address(0)) && (!member) && (memberAddress == address(0))) {
// Add the entrant as a new member of theCyber.
theCyberInterface(THECYBERADDRESS_).newMember(i + 1, bytes32(""), entrant);
}
// Move on to the next entrant / member id.
i++;
}
// Set the index where the function left off; set as inactive if finished.
nextAssigneeIndex_ = i;
if (nextAssigneeIndex_ >= MAXENTRANTS_) {
active_ = false;
}
return true;
}
function nextAssigneeIndex() public view returns(uint8) {
// Return the current assignee index.
return nextAssigneeIndex_;
}
function maxEntrants() public pure returns(uint8) {
// Return the total number of entrants allowed by the gatekeeper.
return MAXENTRANTS_;
}
} | The contract must still be active in order to assign new members. Require a large transaction so that members are added in bulk. All entrants must be registered in order to assign new members. Initialize variables for checking membership statuses. The contract must be a member of theCyber in order to assign new members. Pick up where the function last left off in assigning new members. Loop through entrants as long as sufficient gas remains. Find the entrant at the given index. Determine whether the entrant is already a member of theCyber. Determine whether the target membership is already owned. Ensure that there was no member found with the given id / address. Add the entrant as a new member of theCyber. | function assignAll() public returns (bool) {
require(active_);
require(msg.gas > 6000000);
uint8 totalEntrants = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).totalEntrants();
require(totalEntrants >= MAXENTRANTS_);
bool member;
address memberAddress;
(member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(this);
require(member);
uint8 i = nextAssigneeIndex_;
while (i < MAXENTRANTS_ && msg.gas > 200000) {
address entrant = theCyberGatekeeperTwoInterface(THECYBERGATEKEEPERADDRESS_).entrants(i);
(member,) = theCyberInterface(THECYBERADDRESS_).getMembershipStatus(entrant);
(,,,,memberAddress) = theCyberInterface(THECYBERADDRESS_).getMemberInformation(i + 1);
if ((entrant != address(0)) && (!member) && (memberAddress == address(0))) {
theCyberInterface(THECYBERADDRESS_).newMember(i + 1, bytes32(""), entrant);
}
}
if (nextAssigneeIndex_ >= MAXENTRANTS_) {
active_ = false;
}
return true;
}
| 13,702,950 | [
1,
1986,
6835,
1297,
4859,
506,
2695,
316,
1353,
358,
2683,
394,
4833,
18,
12981,
279,
7876,
2492,
1427,
716,
4833,
854,
3096,
316,
8280,
18,
4826,
31976,
4388,
1297,
506,
4104,
316,
1353,
358,
2683,
394,
4833,
18,
9190,
3152,
364,
6728,
12459,
13516,
18,
1021,
6835,
1297,
506,
279,
3140,
434,
326,
17992,
744,
316,
1353,
358,
2683,
394,
4833,
18,
23038,
731,
1625,
326,
445,
1142,
2002,
3397,
316,
28639,
394,
4833,
18,
9720,
3059,
31976,
4388,
487,
1525,
487,
18662,
16189,
22632,
18,
4163,
326,
31976,
970,
622,
326,
864,
770,
18,
10229,
2856,
326,
31976,
970,
353,
1818,
279,
3140,
434,
326,
17992,
744,
18,
10229,
2856,
326,
1018,
12459,
353,
1818,
16199,
18,
7693,
716,
1915,
1703,
1158,
3140,
1392,
598,
326,
864,
612,
342,
1758,
18,
1436,
326,
31976,
970,
487,
279,
394,
3140,
434,
326,
17992,
744,
18,
2,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | [
1,
225,
445,
2683,
1595,
1435,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
3535,
67,
1769,
203,
203,
565,
2583,
12,
3576,
18,
31604,
405,
1666,
9449,
1769,
203,
203,
565,
2254,
28,
2078,
664,
313,
4388,
273,
326,
17992,
744,
13215,
79,
9868,
11710,
1358,
12,
2455,
7228,
61,
6271,
26316,
6859,
41,
3194,
15140,
67,
2934,
4963,
664,
313,
4388,
5621,
203,
565,
2583,
12,
4963,
664,
313,
4388,
1545,
4552,
2222,
54,
6856,
55,
67,
1769,
203,
203,
565,
1426,
3140,
31,
203,
565,
1758,
3140,
1887,
31,
203,
203,
565,
261,
5990,
16,
13,
273,
326,
17992,
744,
1358,
12,
2455,
7228,
61,
6271,
15140,
67,
2934,
588,
13447,
1482,
12,
2211,
1769,
203,
565,
2583,
12,
5990,
1769,
203,
377,
203,
565,
2254,
28,
277,
273,
1024,
4910,
1340,
1016,
67,
31,
203,
203,
565,
1323,
261,
77,
411,
4552,
2222,
54,
6856,
55,
67,
597,
1234,
18,
31604,
405,
576,
11706,
13,
288,
203,
1377,
1758,
31976,
970,
273,
326,
17992,
744,
13215,
79,
9868,
11710,
1358,
12,
2455,
7228,
61,
6271,
26316,
6859,
41,
3194,
15140,
67,
2934,
8230,
4388,
12,
77,
1769,
203,
203,
1377,
261,
5990,
16,
13,
273,
326,
17992,
744,
1358,
12,
2455,
7228,
61,
6271,
15140,
67,
2934,
588,
13447,
1482,
12,
8230,
970,
1769,
203,
203,
1377,
261,
30495,
5990,
1887,
13,
273,
326,
17992,
744,
1358,
12,
2455,
7228,
61,
6271,
15140,
67,
2934,
588,
4419,
5369,
12,
77,
397,
404,
1769,
203,
4202,
203,
1377,
309,
14015,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
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 {
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;
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 9;
}
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);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
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;
}
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;
}
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Twisted_ESG_Insanity is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
mapping (address => bool) private _isSniper;
bool private _swapping;
uint256 private _launchTime;
address public feeWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = 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 private _buyMarketingFee;
uint256 private _buyLiquidityFee;
uint256 private _buyDevFee;
uint256 public sellTotalFees;
uint256 private _sellMarketingFee;
uint256 private _sellLiquidityFee;
uint256 private _sellDevFee;
uint256 private _tokensForMarketing;
uint256 private _tokensForLiquidity;
uint256 private _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 feeWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Twisted ESG Insanity", "ESG") {
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 = 1;
uint256 buyLiquidityFee = 1;
uint256 buyDevFee = 10;
uint256 sellMarketingFee = 1;
uint256 sellLiquidityFee = 1;
uint256 sellDevFee = 10;
uint256 totalSupply = 1e18 * 1e9;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 3 / 100; // 3% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
_buyMarketingFee = buyMarketingFee;
_buyLiquidityFee = buyLiquidityFee;
_buyDevFee = buyDevFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
_sellMarketingFee = sellMarketingFee;
_sellLiquidityFee = sellLiquidityFee;
_sellDevFee = sellDevFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
feeWallet = address(owner()); // set as fee 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);
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
_launchTime = 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) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * 1e9;
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * 1e9;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_buyMarketingFee = marketingFee;
_buyLiquidityFee = liquidityFee;
_buyDevFee = devFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
require(buyTotalFees <= 10, "Must keep fees at 10% or less");
}
function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_sellMarketingFee = marketingFee;
_sellLiquidityFee = liquidityFee;
_sellDevFee = devFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
require(sellTotalFees <= 15, "Must keep fees at 15% 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 updateFeeWallet(address newWallet) external onlyOwner {
emit feeWalletUpdated(newWallet, feeWallet);
feeWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) {
_isSniper[snipers_[i]] = true;
}
}
}
function delSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
_isSniper[snipers_[i]] = false;
}
}
function isSniper(address addr) public view returns (bool) {
return _isSniper[addr];
}
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");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
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 &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
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
owner(),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
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;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
function withdrawFees() external {
payable(feeWallet).transfer(address(this).balance);
}
receive() external payable {}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Twisted ESG Insanity", "ESG") {
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 = 1;
uint256 buyLiquidityFee = 1;
uint256 buyDevFee = 10;
uint256 sellMarketingFee = 1;
uint256 sellLiquidityFee = 1;
uint256 sellDevFee = 10;
uint256 totalSupply = 1e18 * 1e9;
_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);
| 10,386,498 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
23539,
25444,
14054,
43,
22085,
10417,
3113,
315,
3991,
43,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
540,
203,
3639,
2254,
5034,
30143,
3882,
21747,
14667,
273,
404,
31,
203,
3639,
2254,
5034,
30143,
48,
18988,
24237,
14667,
273,
404,
31,
203,
3639,
2254,
5034,
30143,
8870,
14667,
273,
1728,
31,
203,
203,
3639,
2
] |
./partial_match/1/0xF5cE94caae69Dd5e500123Cecb7AFB6C78826f35/sources/PublicLock.sol | 0x150b7a02 == bytes4(keccak256('onERC721Received(address,address,uint256,bytes)')) The fee relative to keyPrice to charge when transfering a Key to another account (potentially on a 0x marketplace). This is calculated as `keyPrice * transferFeeNumerator / transferFeeDenominator`. | {
using SafeMath for uint;
using Address for address;
event TransferFeeChanged(
uint oldTransferFeeNumerator,
uint oldTransferFeeDenominator,
uint transferFeeNumerator,
uint transferFeeDenominator
);
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
uint public transferFeeNumerator = 0;
uint public transferFeeDenominator = 100;
function transferFrom(
address _from,
address _recipient,
uint _tokenId
)
public
payable
onlyIfAlive
hasValidKey(_from)
onlyKeyOwnerOrApproved(_tokenId)
{
require(_recipient != address(0), 'INVALID_ADDRESS');
_chargeAtLeast(getTransferFee(_from));
Key storage fromKey = _getKeyFor(_from);
Key storage toKey = _getKeyFor(_recipient);
uint previousExpiration = toKey.expirationTimestamp;
if (toKey.tokenId == 0) {
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, toKey.tokenId);
}
if (previousExpiration <= block.timestamp) {
toKey.expirationTimestamp = fromKey.expirationTimestamp;
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, _tokenId);
toKey.expirationTimestamp = fromKey
.expirationTimestamp.add(previousExpiration - block.timestamp);
}
_from,
_recipient,
_tokenId
);
}
{
require(_recipient != address(0), 'INVALID_ADDRESS');
_chargeAtLeast(getTransferFee(_from));
Key storage fromKey = _getKeyFor(_from);
Key storage toKey = _getKeyFor(_recipient);
uint previousExpiration = toKey.expirationTimestamp;
if (toKey.tokenId == 0) {
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, toKey.tokenId);
}
if (previousExpiration <= block.timestamp) {
toKey.expirationTimestamp = fromKey.expirationTimestamp;
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, _tokenId);
toKey.expirationTimestamp = fromKey
.expirationTimestamp.add(previousExpiration - block.timestamp);
}
_from,
_recipient,
_tokenId
);
}
{
require(_recipient != address(0), 'INVALID_ADDRESS');
_chargeAtLeast(getTransferFee(_from));
Key storage fromKey = _getKeyFor(_from);
Key storage toKey = _getKeyFor(_recipient);
uint previousExpiration = toKey.expirationTimestamp;
if (toKey.tokenId == 0) {
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, toKey.tokenId);
}
if (previousExpiration <= block.timestamp) {
toKey.expirationTimestamp = fromKey.expirationTimestamp;
toKey.tokenId = fromKey.tokenId;
_recordOwner(_recipient, _tokenId);
toKey.expirationTimestamp = fromKey
.expirationTimestamp.add(previousExpiration - block.timestamp);
}
_from,
_recipient,
_tokenId
);
}
} else {
fromKey.expirationTimestamp = block.timestamp;
fromKey.tokenId = 0;
_clearApproval(_tokenId);
emit Transfer(
function safeTransferFrom(
address _from,
address _to,
uint _tokenId
)
external
payable
{
safeTransferFrom(_from, _to, _tokenId, '');
}
function safeTransferFrom(
address _from,
address _to,
uint _tokenId,
bytes memory _data
)
public
payable
onlyIfAlive
onlyKeyOwnerOrApproved(_tokenId)
hasValidKey(ownerOf(_tokenId))
{
transferFrom(_from, _to, _tokenId);
require(_checkOnERC721Received(_from, _to, _tokenId, _data), 'NON_COMPLIANT_ERC721_RECEIVER');
}
function updateTransferFee(
uint _transferFeeNumerator,
uint _transferFeeDenominator
)
external
onlyOwner
{
require(_transferFeeDenominator != 0, 'INVALID_RATE');
emit TransferFeeChanged(
transferFeeNumerator,
transferFeeDenominator,
_transferFeeNumerator,
_transferFeeDenominator
);
transferFeeNumerator = _transferFeeNumerator;
transferFeeDenominator = _transferFeeDenominator;
}
function getTransferFee(
address _owner
)
public view
hasValidKey(_owner)
returns (uint)
{
Key storage key = _getKeyFor(_owner);
uint timeRemaining = key.expirationTimestamp - block.timestamp;
uint fee;
if(timeRemaining >= expirationDuration) {
fee = keyPrice;
fee = keyPrice.mul(timeRemaining) / expirationDuration;
}
return fee.mul(transferFeeNumerator) / transferFeeDenominator;
}
function getTransferFee(
address _owner
)
public view
hasValidKey(_owner)
returns (uint)
{
Key storage key = _getKeyFor(_owner);
uint timeRemaining = key.expirationTimestamp - block.timestamp;
uint fee;
if(timeRemaining >= expirationDuration) {
fee = keyPrice;
fee = keyPrice.mul(timeRemaining) / expirationDuration;
}
return fee.mul(transferFeeNumerator) / transferFeeDenominator;
}
} else {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
| 16,171,220 | [
1,
20,
92,
23014,
70,
27,
69,
3103,
422,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2506,
3719,
1021,
14036,
3632,
358,
498,
5147,
358,
13765,
1347,
7412,
310,
279,
1929,
358,
4042,
2236,
261,
13130,
11220,
603,
279,
374,
92,
29917,
2934,
1220,
353,
8894,
487,
1375,
856,
5147,
225,
7412,
14667,
2578,
7385,
342,
7412,
14667,
8517,
26721,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
225,
1450,
14060,
10477,
364,
2254,
31,
203,
225,
1450,
5267,
364,
1758,
31,
203,
203,
225,
871,
12279,
14667,
5033,
12,
203,
565,
2254,
1592,
5912,
14667,
2578,
7385,
16,
203,
565,
2254,
1592,
5912,
14667,
8517,
26721,
16,
203,
565,
2254,
7412,
14667,
2578,
7385,
16,
203,
565,
2254,
7412,
14667,
8517,
26721,
203,
225,
11272,
203,
203,
225,
1731,
24,
3238,
5381,
389,
654,
39,
27,
5340,
67,
27086,
20764,
273,
374,
92,
23014,
70,
27,
69,
3103,
31,
203,
203,
225,
2254,
1071,
7412,
14667,
2578,
7385,
273,
374,
31,
203,
225,
2254,
1071,
7412,
14667,
8517,
26721,
273,
2130,
31,
203,
203,
225,
445,
7412,
1265,
12,
203,
565,
1758,
389,
2080,
16,
203,
565,
1758,
389,
20367,
16,
203,
565,
2254,
389,
2316,
548,
203,
225,
262,
203,
565,
1071,
203,
565,
8843,
429,
203,
565,
1338,
2047,
10608,
203,
565,
711,
1556,
653,
24899,
2080,
13,
203,
565,
1338,
653,
5541,
1162,
31639,
24899,
2316,
548,
13,
203,
203,
203,
225,
288,
203,
565,
2583,
24899,
20367,
480,
1758,
12,
20,
3631,
296,
9347,
67,
15140,
8284,
203,
565,
389,
16385,
25070,
12,
588,
5912,
14667,
24899,
2080,
10019,
203,
203,
565,
1929,
2502,
628,
653,
273,
389,
588,
653,
1290,
24899,
2080,
1769,
203,
565,
1929,
2502,
358,
653,
273,
389,
588,
653,
1290,
24899,
20367,
1769,
203,
203,
565,
2254,
2416,
12028,
273,
358,
653,
18,
19519,
4921,
31,
203,
203,
565,
309,
261,
869,
653,
18,
2316,
548,
422,
374,
13,
288,
2
] |
/* website: padthai.finance
**
** βββββββββ βββββββββ βββββββββ βββ ββ ββ βββββββββ ββ
** βββ βββ βββ βββ βββ ββββ βββββββββββ βββ βββ βββ βββ βββ
** βββ βββ βββ βββ βββ βββ ββββββββ βββ βββ βββ βββ ββββ
** βββ βββ βββ βββ βββ βββ βββ β βββββββββββββ βββ βββ ββββ
** βββββββββββ ββββββββββββ βββ βββ βββ βββββββββββββ ββββββββββββ ββββ
** βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ
** βββ βββ βββ βββ ββββ βββ βββ βββ βββ βββ βββ
** ββββββ βββ ββ βββββββββ ββββββ βββ ββ βββ ββ ββ
**
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 { }
}
// File: contracts/PadThaiToken.sol
/* website: padthai.finance
**
** βββββββββ βββββββββ βββββββββ βββ ββ ββ βββββββββ ββ
** βββ βββ βββ βββ βββ ββββ βββββββββββ βββ βββ βββ βββ βββ
** βββ βββ βββ βββ βββ βββ ββββββββ βββ βββ βββ βββ ββββ
** βββ βββ βββ βββ βββ βββ βββ β βββββββββββββ βββ βββ ββββ
** βββββββββββ ββββββββββββ βββ βββ βββ βββββββββββββ ββββββββββββ ββββ
** βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ
** βββ βββ βββ βββ ββββ βββ βββ βββ βββ βββ βββ
** ββββββ βββ ββ βββββββββ ββββββ βββ ββ βββ ββ ββ
**
*/
pragma solidity 0.6.12;
contract PadThaiToken is ERC20("padthai.finance", "PADTHAI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (PadThaiChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
// File: contracts/PadThaiChef.sol
pragma solidity 0.6.12;
// PadThaiChef is the master of Padthai. He can make Padthai and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once PADTHAI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract PadThaiChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PADTHAIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPadthaiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPadthaiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. PADTHAIs to distribute per block.
uint256 lastRewardBlock; // Last block number that PADTHAIs distribution occurs.
uint256 accPadthaiPerShare; // Accumulated PADTHAIs per share, times 1e12. See below.
}
// The PADTHAI TOKEN!
PadThaiToken public padthai;
// Dev address.
address public devaddr;
// Block number when bonus PADTHAI period ends.
uint256 public bonusEndBlock;
// PADTHAI tokens created per block.
uint256 public padthaiPerBlock;
// Bonus muliplier for early padthai makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when PADTHAI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
PadThaiToken _padthai,
address _devaddr,
uint256 _padthaiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
padthai = _padthai;
devaddr = _devaddr;
padthaiPerBlock = _padthaiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// PeckShield Audit recommendation
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function checkPoolDuplicate (IERC20 _lpToken) public {
uint256 length = poolInfo.length ;
for (uint256 _pid = 0; _pid < length; ++_pid) {
require(poolInfo[_pid].lpToken != _lpToken, "add:existingpool?");
}
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
checkPoolDuplicate (_lpToken);
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accPadthaiPerShare: 0
}));
}
// Update the given pool's PADTHAI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending PADTHAIs on frontend.
function pendingPadthai(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPadthaiPerShare = pool.accPadthaiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 padthaiReward = multiplier.mul(padthaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accPadthaiPerShare = accPadthaiPerShare.add(padthaiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accPadthaiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 padthaiReward = multiplier.mul(padthaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
padthai.mint(devaddr, padthaiReward.div(10));
padthai.mint(address(this), padthaiReward);
pool.accPadthaiPerShare = pool.accPadthaiPerShare.add(padthaiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to PadThaiChef for PADTHAI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accPadthaiPerShare).div(1e12).sub(user.rewardDebt);
safePadthaiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accPadthaiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from PadThaiChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accPadthaiPerShare).div(1e12).sub(user.rewardDebt);
safePadthaiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accPadthaiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe padthai transfer function, just in case if rounding error causes pool to not have enough PADTHAIs.
function safePadthaiTransfer(address _to, uint256 _amount) internal {
uint256 padthaiBal = padthai.balanceOf(address(this));
if (_amount > padthaiBal) {
padthai.transfer(_to, padthaiBal);
} else {
padthai.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | View function to see pending PADTHAIs on frontend. | function pendingPadthai(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPadthaiPerShare = pool.accPadthaiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 padthaiReward = multiplier.mul(padthaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accPadthaiPerShare = accPadthaiPerShare.add(padthaiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accPadthaiPerShare).div(1e12).sub(user.rewardDebt);
}
| 7,976,973 | [
1,
1767,
445,
358,
2621,
4634,
453,
1880,
2455,
37,
2520,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4634,
14878,
451,
10658,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
14878,
451,
10658,
2173,
9535,
273,
2845,
18,
8981,
14878,
451,
10658,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
5411,
2254,
5034,
4627,
451,
10658,
17631,
1060,
273,
15027,
18,
16411,
12,
6982,
451,
10658,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
5411,
4078,
14878,
451,
10658,
2173,
9535,
273,
4078,
14878,
451,
10658,
2173,
9535,
18,
1289,
12,
6982,
451,
10658,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
14878,
451,
10658,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x2EeD3521d59F8f848CdE7E94C36EB3b363159764/sources/JCTNFT.sol | ε‘ηη§―εε’ηη³»ζ°εεζ΄ TODO δΉδ»₯amount | ownerPointCoefficients[_to] = ownerPointCoefficients[_to].add(cardPointCoefficient[_id].mul(_amount));
| 8,652,994 | [
1,
166,
240,
99,
168,
236,
239,
168,
105,
112,
166,
235,
233,
166,
100,
257,
168,
254,
237,
168,
116,
124,
167,
248,
113,
166,
245,
239,
166,
242,
251,
167,
254,
117,
2660,
225,
165,
122,
251,
165,
124,
103,
8949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3410,
2148,
4249,
73,
12344,
63,
67,
869,
65,
273,
3410,
2148,
4249,
73,
12344,
63,
67,
869,
8009,
1289,
12,
3327,
2148,
4249,
25403,
63,
67,
350,
8009,
16411,
24899,
8949,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xD4590A43DbcBEF5DBfE3C80cc8d37e574d512B1A/sources/contracts/transferVesting.sol | * @dev Sets the uniswapV2 pair (router & factory) for swapping and liquifying tokens/ | function setRouterAddress(address router) external onlyManager {
_setRouterAddress(router);
}
| 9,503,788 | [
1,
2785,
326,
640,
291,
91,
438,
58,
22,
3082,
261,
10717,
473,
3272,
13,
364,
7720,
1382,
471,
4501,
372,
1164,
310,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
8259,
1887,
12,
2867,
4633,
13,
3903,
1338,
1318,
288,
203,
3639,
389,
542,
8259,
1887,
12,
10717,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at BscScan.com on 2021-03-03
*/
// SPDX-License-Identifier: MIT
/* BNBStake - investment platform based on Binance Smart Chain blockchain smart-contract technology. Safe and legit!
* The only official platform of original TronStake team! All other platforms with the same contract code are FAKE!
*
* ______ _ _ ______ _____ _ _
* | ___ \ \ | || ___ \/ ___| | | |
* | |_/ / \| || |_/ /\ `--.| |_ __ _| | _____ BNBStake.app
* | ___ \ . ` || ___ \ `--. \ __/ _` | |/ / _ \ by AV
* | |_/ / |\ || |_/ //\__/ / || (_| | < __/
* \____/\_| \_/\____/ \____/ \__\__,_|_|\_\___|
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* β Website: https://bnbstake.app β
* β β
* β Telegram Live Support: @bnbstake_support |
* β Telegram Public Group: https://t.me/bnb_stake |
* | |
* | E-mail: [email protected] |
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*
* [USAGE INSTRUCTION]
*
* 1) Connect browser extension Metamask (see help: https://academy.binance.com/en/articles/connecting-metamask-to-binance-smart-chain )
* 2) Choose one of the tariff plans, enter the BNB amount (0.05 BNB minimum) using our website "Stake BNB" button
* 3) Wait for your earnings
* 4) Withdraw earnings any time using our website "Withdraw" button
*
* [INVESTMENT CONDITIONS]
*
* - Basic interest rate: +0.5% every 24 hours (~0.02% hourly) - only for new deposits
* - Minimal deposit: 0.05 BNB, no maximal limit
* - Total income: based on your tarrif plan (from 5% to 8% daily!!!) + Basic interest rate !!!
* - Earnings every moment, withdraw any time (if you use capitalization of interest you can withdraw only after end of your deposit)
*
* [AFFILIATE PROGRAM]
*
* - 3-level referral commission: 5% - 2.5% - 0.5%
*
* [FUNDS DISTRIBUTION]
*
* - 82% Platform main balance, participants payouts
* - 8% Advertising and promotion expenses
* - 8% Affiliate program bonuses
* - 2% Support work, technical functioning, administration fee
*/
/**
* A partir de aqui se encontraran comentarios explicativos del codigo que no vienen en el codigo original
*/
pragma solidity >=0.4.22 <0.9.0;
contract BNBStake {
using SafeMath for uint256;
uint256 constant public INVEST_MIN_AMOUNT = 0.05 ether;
uint256[] public REFERRAL_PERCENTS = [50, 25, 5];
uint256 constant public PROJECT_FEE = 100;
uint256 constant public PERCENT_STEP = 5;
uint256 constant public PERCENTS_DIVIDER = 1000;
uint256 constant public TIME_STEP = 1 days;
uint256 public totalStaked;
uint256 public totalRefBonus;
// Esta struct
struct Plan {
uint256 time;
uint256 percent;
}
Plan[] internal plans;
// Struct que guarda informacion del deposito
struct Deposit {
uint8 plan; // Identificador del plan elegido
uint256 percent; // Porcentaje con el que se deposito en ese plan
uint256 amount; // Cantidad que se deposito
uint256 profit; // Cantidad a devolver
uint256 start; // fecha (en segundos) en el que se deposito
uint256 finish; // fecha (en segundos) en el que se podra sacar (de estar bloqueada la cantidad)
}
struct User {
Deposit[] deposits;
uint256 checkpoint;
address referrer;
uint256[3] levels;
uint256 bonus;
uint256 totalBonus;
}
mapping (address => User) internal users;
uint256 public startUNIX;
address payable public commissionWallet;
event Newbie(address user);
event NewDeposit(address indexed user, uint8 plan, uint256 percent, uint256 amount, uint256 profit, uint256 start, uint256 finish);
event Withdrawn(address indexed user, uint256 amount);
event RefBonus(address indexed referrer, address indexed referral, uint256 indexed level, uint256 amount);
event FeePayed(address indexed user, uint256 totalAmount);
constructor(address payable wallet, uint256 startDate) public {
require(!isContract(wallet));
require(startDate > 0);
commissionWallet = wallet;
startUNIX = startDate;
plans.push(Plan(14, 80));
plans.push(Plan(21, 65));
plans.push(Plan(28, 50));
plans.push(Plan(14, 80));
plans.push(Plan(21, 65));
plans.push(Plan(28, 50));
}
// payable hace que para llamar a esta funcion se le puede pagar un coste junto a la llamada
// El coste pagado (se entiende) se anade implicitamente al balance del contrato
/**
* invest es la funcion que incrementa los bonuses de los referidos, crea un nuevo User y lo guarda en el mapa
* de no existir este y guarda el deposito pedido en funcion del plan.
* params: referrer -> el address del referido
* params: plan -> Byte que indica el plan elegido
*/
function invest(address referrer, uint8 plan) public payable {
require(msg.value >= INVEST_MIN_AMOUNT);
require(plan < 6, "Invalid plan");
// Comision que se lleva el creador del contrato (10 % por investment)
uint256 fee = msg.value.mul(PROJECT_FEE).div(PERCENTS_DIVIDER);
commissionWallet.transfer(fee);
emit FeePayed(msg.sender, fee);
//Creacion del nuevo usuario (si no existe), si existe se guarda en user
User storage user = users[msg.sender];
// Si no tiene referrer (por que es nuevo o porque en su momento)
if (user.referrer == address(0)) {
// Si el refferer ya tiene investment y el referrer no es el user que llama a la funcion
if (users[referrer].deposits.length > 0 && referrer != msg.sender) {
//asigna el referrer con el que se ha llamadao la funcion
user.referrer = referrer;
}
// Adicion de referidos, 3 niveles de referrers
address upline = user.referrer;
for (uint256 i = 0; i < 3; i++) {
if (upline != address(0)) {
users[upline].levels[i] = users[upline].levels[i].add(1); // ΒΏPor que le anade uno?
upline = users[upline].referrer; // Avanzar al siguiente referrer
} else break;
}
}
if (user.referrer != address(0)) {
// Aumento de los bonus amount a cada referrer en funcion de su nivel
address upline = user.referrer;
for (uint256 i = 0; i < 3; i++) { // Tres iteraciones, tres niveles de referral
if (upline != address(0)) {
uint256 amount = msg.value.mul(REFERRAL_PERCENTS[i]).div(PERCENTS_DIVIDER); // Cuanto mas bajo el nivel
users[upline].bonus = users[upline].bonus.add(amount);
users[upline].totalBonus = users[upline].totalBonus.add(amount); // Esta variable (totalBonus) no se utiliza, asignacion y memoria inservibles
emit RefBonus(upline, msg.sender, i, amount); //Evento emitido
upline = users[upline].referrer; // Avanzar al siguiente referral
} else break;
}
}
// Si el usuario no tiene depositos
if (user.deposits.length == 0) {
user.checkpoint = block.timestamp; // Timestamp en segundos
emit Newbie(msg.sender);
}
(uint256 percent, uint256 profit, uint256 finish) = getResult(plan, msg.value); // Calcula los valores a retornar del plan elegido
user.deposits.push(Deposit(plan, percent, msg.value, profit, block.timestamp, finish)); // Pusheo a la lista del Objeto Deposit
totalStaked = totalStaked.add(msg.value); // Actualizacion de la variable que tiene el bnb stakeado del contrato (No se decrementa)
emit NewDeposit(msg.sender, plan, percent, msg.value, profit, block.timestamp, finish); // Emision del evento
}
function withdraw() public {
User storage user = users[msg.sender];
uint256 totalAmount = getUserDividends(msg.sender);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function getPlanInfo(uint8 plan) public view returns(uint256 time, uint256 percent) {
time = plans[plan].time;
percent = plans[plan].percent;
}
function getPercent(uint8 plan) public view returns (uint256) {
if (block.timestamp > startUNIX) {
return plans[plan].percent.add(PERCENT_STEP.mul(block.timestamp.sub(startUNIX)).div(TIME_STEP));
} else {
return plans[plan].percent;
}
}
function getResult(uint8 plan, uint256 deposit) public view returns (uint256 percent, uint256 profit, uint256 finish) {
percent = getPercent(plan);
if (plan < 3) {
profit = deposit.mul(percent).div(PERCENTS_DIVIDER).mul(plans[plan].time);
} else if (plan < 6) {
for (uint256 i = 0; i < plans[plan].time; i++) {
profit = profit.add((deposit.add(profit)).mul(percent).div(PERCENTS_DIVIDER));
}
}
finish = block.timestamp.add(plans[plan].time.mul(TIME_STEP));
}
function getUserDividends(address userAddress) public view returns (uint256) {
User storage user = users[userAddress];
uint256 totalAmount;
for (uint256 i = 0; i < user.deposits.length; i++) {
if (user.checkpoint < user.deposits[i].finish) {
if (user.deposits[i].plan < 3) {
uint256 share = user.deposits[i].amount.mul(user.deposits[i].percent).div(PERCENTS_DIVIDER);
uint256 from = user.deposits[i].start > user.checkpoint ? user.deposits[i].start : user.checkpoint;
uint256 to = user.deposits[i].finish < block.timestamp ? user.deposits[i].finish : block.timestamp;
if (from < to) {
totalAmount = totalAmount.add(share.mul(to.sub(from)).div(TIME_STEP));
}
} else if (block.timestamp > user.deposits[i].finish) {
totalAmount = totalAmount.add(user.deposits[i].profit);
}
}
}
return totalAmount;
}
function getUserCheckpoint(address userAddress) public view returns(uint256) {
return users[userAddress].checkpoint;
}
function getUserReferrer(address userAddress) public view returns(address) {
return users[userAddress].referrer;
}
function getUserDownlineCount(address userAddress) public view returns(uint256, uint256, uint256) {
return (users[userAddress].levels[0], users[userAddress].levels[1], users[userAddress].levels[2]);
}
function getUserReferralBonus(address userAddress) public view returns(uint256) {
return users[userAddress].bonus;
}
function getUserReferralTotalBonus(address userAddress) public view returns(uint256) {
return users[userAddress].totalBonus;
}
function getUserReferralWithdrawn(address userAddress) public view returns(uint256) {
return users[userAddress].totalBonus.sub(users[userAddress].bonus);
}
function getUserAvailable(address userAddress) public view returns(uint256) {
return getUserReferralBonus(userAddress).add(getUserDividends(userAddress));
}
function getUserAmountOfDeposits(address userAddress) public view returns(uint256) {
return users[userAddress].deposits.length;
}
function getUserTotalDeposits(address userAddress) public view returns(uint256 amount) {
for (uint256 i = 0; i < users[userAddress].deposits.length; i++) {
amount = amount.add(users[userAddress].deposits[i].amount);
}
}
function getUserDepositInfo(address userAddress, uint256 index) public view returns(uint8 plan, uint256 percent, uint256 amount, uint256 profit, uint256 start, uint256 finish) {
User storage user = users[userAddress];
plan = user.deposits[index].plan;
percent = user.deposits[index].percent;
amount = user.deposits[index].amount;
profit = user.deposits[index].profit;
start = user.deposits[index].start;
finish = user.deposits[index].finish;
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
} | Struct que guarda informacion del deposito | struct Deposit {
}
| 1,083,900 | [
1,
3823,
6597,
11026,
69,
13235,
19861,
1464,
443,
1724,
83,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
1697,
4019,
538,
305,
288,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol | @dev Reads the uint152 at `rdPtr` in returndata. | function readUint152(
ReturndataPointer rdPtr
) internal pure returns (uint152 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 4,300,445 | [
1,
7483,
326,
2254,
27655,
622,
1375,
13623,
5263,
68,
316,
327,
892,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
855,
5487,
27655,
12,
203,
3639,
2000,
892,
4926,
9437,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
27655,
460,
13,
288,
203,
3639,
19931,
288,
203,
5411,
327,
892,
3530,
12,
20,
16,
9437,
5263,
16,
389,
3335,
3944,
13,
203,
5411,
460,
519,
312,
945,
12,
20,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-06-08
*/
pragma solidity ^0.6.7;
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function ceil(uint a, uint m) internal pure returns (uint) {
uint c = add(a,m);
uint d = sub(c,1);
return mul(div(d,m),m);
}
}
abstract contract Uniswap2PairContract {
function getReserves() external virtual returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}
abstract contract ERC20Token {
function totalSupply() public virtual returns (uint);
function approve(address spender, uint value) public virtual returns (bool);
function balanceOf(address owner) public virtual returns (uint);
function transferFrom (address from, address to, uint value) public virtual returns (bool);
}
contract Ownable {
address public owner;
event TransferOwnership(address _from, address _to);
constructor() public {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
modifier onlyOwner() {
require(msg.sender == owner, "only owner");
_;
}
function setOwner(address _owner) external onlyOwner {
emit TransferOwnership(owner, _owner);
owner = _owner;
}
}
contract UniBOMBLiquidReward is Ownable{
using SafeMath for uint;
uint ONE_MONTH = 60*60*24*30;
uint MAX_MONTHS = 12;
address public LIQUIDITY_TOKEN = 0xEE89ea23c18410F2b57e7abc6eb24cfcdE4f49B0;
address public REWARD_TOKEN = 0xbBB38bE7c6D954320c0297c06Ab3265a950CDF89;
uint[3] public rewardLevels = [10000,20000,30000];
uint[3] public poolLevels = [100000000000000000000,1000000000000000000000,10000000000000000000000];
uint[3] public monthLevels = [3,6,12];
uint[4] public baseRateLookup = [250,200,150,100];
//poolLevelsIndex //monthLevelsIndex //s0(small)[m0,m1,m2..] //s2 m2 m3 /3=
uint[4][4] public multiplierLookup = [[105,110,120,130],[100,105,110,120],[100,100,105,110],[100,100,100,100]];
mapping(address => mapping(uint => LiquidityRewardData)) public liquidityRewardData; //address to timestamp to data
uint public allocatedRewards;
uint public totalUniswapLiquidity;
uint public unallocatedRewards;
struct LiquidityRewardData {
uint quantity;
uint timestamp;
uint stakeMonths;
uint reward;
bool rewardClaimed;
bool liquidityClaimed;
}
fallback() external payable {
revert();
}
function setRewardLevels(uint[3] memory input ) public onlyOwner{
rewardLevels = input;
}
function setpoolLevels(uint[3] memory input ) public onlyOwner{
poolLevels = input;
}
function setMonthLevels(uint[3] memory input ) public onlyOwner{
monthLevels = input;
}
function setBaseRateLookup(uint[4] memory input ) public onlyOwner{
baseRateLookup = input;
}
function setMultiplierLookup(uint[4][4] memory input ) public onlyOwner{
multiplierLookup = input;
}
function setMaxMonths(uint input ) public onlyOwner{
MAX_MONTHS = input;
}
function getMaxMonths() view public returns(uint){
return MAX_MONTHS;
}
function getAllocatedRewards() view public returns(uint){
return allocatedRewards;
}
function getUnallocatedRewards() view public returns(uint){
return unallocatedRewards;
}
function findOnePercent(uint256 value) public pure returns (uint256) {
uint256 roundValue = value.ceil(100);
uint256 onePercent = roundValue.mul(100).div(10000);
return onePercent;
}
//(this)must be whitelisted on ubomb
function topupReward (uint amount) external {
require(ERC20Token(REWARD_TOKEN).transferFrom(address(msg.sender), address(this), amount),"tokenXferFail");
//calc actual deposit amount due to BOMB burn
uint tokensToBurn = findOnePercent(amount);
uint actual = amount.sub(tokensToBurn);
unallocatedRewards += actual;
}
function removeReward () external onlyOwner {
require(ERC20Token(REWARD_TOKEN).transferFrom(address(this), address(msg.sender), unallocatedRewards),"tokenXferFail");
unallocatedRewards = 0;
}
function calcReward(uint stakeMonths, uint stakeTokens) public returns (uint){
(uint tokens, uint eth, uint time) = Uniswap2PairContract(LIQUIDITY_TOKEN).getReserves();
uint liquidity = stakeTokens;
uint liquidityTotalSupply = ERC20Token(LIQUIDITY_TOKEN).totalSupply();
//uint amountEth = liquidity.mul(eth) / liquidityTotalSupply; // using balances ensures pro-rata distribution
uint amountTokens = (liquidity.mul(tokens)).div(liquidityTotalSupply); // using balances ensures pro-rata distribution
uint months = stakeMonths;
uint baseRate = baseRateLookup[getRewardIndex()];
uint multiplier = multiplierLookup[getpoolLevelsIndex(eth)][getMonthsIndex(months)];
uint reward = (amountTokens.mul(months).mul(baseRate).mul(multiplier)).div(1000000);
return(reward);
}
function getRewardIndex() public view returns (uint) {
if(unallocatedRewards < rewardLevels[0]){return 3;}
else if(unallocatedRewards < rewardLevels[1]){return 2;}
else if(unallocatedRewards < rewardLevels[2]){return 1;}
else {return 0;}
}
//baserate
function getpoolLevelsIndex(uint eth) public view returns (uint) {
if(eth < poolLevels[0] ){return 0;}
else if(eth <poolLevels[1]){return 1;}
else if(eth <poolLevels[2]){return 2;}
else {return 3;}
}
function getMonthsIndex(uint month) public view returns (uint) {
if(month < monthLevels[0]){return 0;}
else if(month < monthLevels[1]){return 1;}
else if(month < monthLevels[2]){return 2;}
else {return 3;}
}
function lockLiquidity(uint idx, uint stakeMonths, uint stakeTokens) external {
//temp hold tokens and ether from sender
require(stakeMonths <= MAX_MONTHS,"tooManyMonths");
require(ERC20Token(LIQUIDITY_TOKEN).transferFrom(address(msg.sender), address(this), stakeTokens),"tokenXferFail");
require( (liquidityRewardData[msg.sender][idx].quantity == 0),"previousLiquidityInSlot");
uint reward = calcReward(stakeMonths,stakeTokens);
require( unallocatedRewards >= reward, "notEnoughRewardRemaining");
allocatedRewards += reward;
unallocatedRewards -= reward;
totalUniswapLiquidity += stakeTokens;
liquidityRewardData[msg.sender][idx] = LiquidityRewardData(stakeTokens, block.timestamp, stakeMonths, reward,false,false);
}
function rewardTask(uint idx, uint renewMonths) public {
require(liquidityRewardData[msg.sender][idx].rewardClaimed == false,"RewardClaimedAlready");
liquidityRewardData[msg.sender][idx].rewardClaimed = true;
uint reward = liquidityRewardData[msg.sender][idx].reward;
allocatedRewards -= reward;
if( liquidityRewardData[msg.sender][idx].timestamp.add( liquidityRewardData[msg.sender][idx].stakeMonths.mul(ONE_MONTH)) <= block.timestamp){
if(renewMonths > 0 && liquidityRewardData[msg.sender][idx].liquidityClaimed==false){ //claim and renew
uint newReward = calcReward(renewMonths,liquidityRewardData[msg.sender][idx].quantity);
require(newReward < unallocatedRewards,"NotEnoughRewardsRemaining");
allocatedRewards += newReward;
unallocatedRewards -= newReward;
liquidityRewardData[msg.sender][idx].timestamp = block.timestamp;
liquidityRewardData[msg.sender][idx].stakeMonths = renewMonths;
liquidityRewardData[msg.sender][idx].reward = newReward;
liquidityRewardData[msg.sender][idx].rewardClaimed = false;
}
ERC20Token(REWARD_TOKEN).approve(address(this),reward);
ERC20Token(REWARD_TOKEN).transferFrom(address(this), address(msg.sender), reward);
}
else{
unallocatedRewards += reward;
}
}
function unlockLiquidity(uint idx) external { //get liquidity tokens
require(liquidityRewardData[msg.sender][idx].liquidityClaimed == false,"LiquidityAlreadyClaimed");
if(liquidityRewardData[msg.sender][idx].rewardClaimed == false){
rewardTask(idx,0);
}
totalUniswapLiquidity -= liquidityRewardData[msg.sender][idx].quantity;
ERC20Token(LIQUIDITY_TOKEN).approve(address(this),liquidityRewardData[msg.sender][idx].quantity);
ERC20Token(LIQUIDITY_TOKEN).transferFrom(address(this),address(msg.sender),liquidityRewardData[msg.sender][idx].quantity);
liquidityRewardData[msg.sender][idx].quantity = 0;
liquidityRewardData[msg.sender][idx].liquidityClaimed = true;
}
} | (this)must be whitelisted on ubombcalc actual deposit amount due to BOMB burn | function topupReward (uint amount) external {
require(ERC20Token(REWARD_TOKEN).transferFrom(address(msg.sender), address(this), amount),"tokenXferFail");
uint tokensToBurn = findOnePercent(amount);
uint actual = amount.sub(tokensToBurn);
unallocatedRewards += actual;
}
| 2,326,459 | [
1,
12,
2211,
13,
11926,
506,
26944,
603,
13910,
16659,
12448,
3214,
443,
1724,
3844,
6541,
358,
25408,
38,
18305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
1760,
416,
17631,
1060,
261,
11890,
3844,
13,
225,
3903,
288,
203,
4202,
2583,
12,
654,
39,
3462,
1345,
12,
862,
21343,
67,
8412,
2934,
13866,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
3844,
3631,
6,
2316,
60,
586,
3754,
8863,
203,
4202,
2254,
2430,
774,
38,
321,
273,
9525,
8410,
12,
8949,
1769,
203,
4202,
2254,
3214,
273,
3844,
18,
1717,
12,
7860,
774,
38,
321,
1769,
203,
3639,
203,
4202,
640,
28172,
17631,
14727,
1011,
3214,
31,
203,
377,
289,
7010,
1377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-25
*/
pragma solidity 0.8.7;
// SPDX-License-Identifier: Unlicensed
pragma abicoder v2;
interface IERC20 {
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);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
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;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toETHSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n Γ· 2 + 1, and for v in (282): v β {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an ETHereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ETHereum/wiki/wiki/JSON-RPC#ETH_sign[`ETH_sign`]
* JSON-RPC mETHod.
*
* See {recover}.
*/
function toETHSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract EliteBridge is Ownable {
struct userDetails {
uint amount;
address token;
uint lastTransaction;
}
// ECDSA Address
using ECDSA for address;
address public signer;
bool public lockStatus;
event SetSigner(address indexed user,address indexed signer);
event Deposit(address indexed user,uint amount,address indexed token,uint time);
event Claim(address indexed user,address indexed token,uint amount,uint time);
event Fallback(address indexed user,uint amount,uint time);
event Failsafe(address indexed user, address indexed tokenAddress,uint amount);
mapping(bytes32 => bool)public msgHash;
mapping(address => mapping(address => userDetails))public UserInfo;
mapping (address => bool) public isApproved;
constructor (address _signer) {
signer = _signer;
}
/**
* @dev Throws if lockStatus is true
*/
modifier isLock() {
require(lockStatus == false, "Elite: Contract Locked");
_;
}
modifier isApprove(address _token){
require(isApproved[_token],"Un approve token");
_;
}
/**
* @dev Throws if called by other contract
*/
modifier isContractCheck(address _user) {
require(!isContract(_user), "Elite: Invalid address");
_;
}
function addToken(address _tokenAddress,uint _amount) public onlyOwner {
require(_amount > 0,"Invalid amount");
IERC20(_tokenAddress).transferFrom(msg.sender,address(this),_amount);
}
receive()external payable {
emit Fallback(msg.sender,msg.value,block.timestamp);
}
function approveTokenToDeposit(address _tokenAddress, bool _approveStatus) external onlyOwner {
isApproved[_tokenAddress] = _approveStatus;
}
function deposit(address _tokenAddress, uint _amount)public isLock isApprove(_tokenAddress){
require (_amount > 0,"Incorrect params");
userDetails storage users = UserInfo[msg.sender][_tokenAddress];
IERC20(_tokenAddress).transferFrom(msg.sender,address(this),_amount);
users.token = _tokenAddress;
users.amount = _amount;
users.lastTransaction = block.timestamp;
emit Deposit(msg.sender,_amount,_tokenAddress,block.timestamp);
}
function claim(address _user,address _tokenAddress,uint amount, bytes calldata signature,uint _time) public isLock isApprove(_tokenAddress) {
//messageHash can be used only once
require(_time > block.timestamp,"signature Expiry");
bytes32 messageHash = message(_user, _tokenAddress,amount,_time);
require(!msgHash[messageHash], "claim: signature duplicate");
//Verifes signature
address src = verifySignature(messageHash, signature);
require(signer == src, " claim: unauthorized");
IERC20(_tokenAddress).transfer(_user,amount);
msgHash[messageHash] = true;
emit Claim(_user,_tokenAddress,amount,block.timestamp);
}
/**
* @dev ETHereum Signed Message, created from `hash`
* @dev Returns the address that signed a hashed message (`hash`) with `signature`.
*/
function verifySignature(bytes32 _messageHash, bytes memory _signature) public pure returns (address signatureAddress)
{
bytes32 hash = ECDSA.toETHSignedMessageHash(_messageHash);
signatureAddress = ECDSA.recover(hash, _signature);
}
/**
* @dev Returns hash for given data
*/
function message(address _receiver, address _tokenAdderss ,uint amount,uint time)
public pure returns(bytes32 messageHash)
{
messageHash = keccak256(abi.encodePacked(_receiver, _tokenAdderss,amount,time));
}
// updaate signer address
function setSigner(address _signer)public onlyOwner{
signer = _signer;
emit SetSigner(msg.sender, _signer);
}
function failsafe(address user,address tokenAddress,uint amount)public onlyOwner{
if(tokenAddress == address(0x0)){
payable(user).transfer(amount);
}else {
IERC20(tokenAddress).transfer(user,amount);
}
emit Failsafe(user, tokenAddress,amount);
}
function checkBalance()public view returns(uint){
return address(this).balance;
}
/**
* @dev contractLock: For contract status
*/
function contractLock(bool _lockStatus) public onlyOwner returns(bool) {
lockStatus = _lockStatus;
return true;
}
/**
* @dev isContract: Returns true if account is a contract
*/
function isContract(address _account) public view returns(bool) {
uint32 size;
assembly {
size:= extcodesize(_account)
}
if (size != 0)
return true;
return false;
}
} | * @dev Returns hash for given data/ | function message(address _receiver, address _tokenAdderss ,uint amount,uint time)
public pure returns(bytes32 messageHash)
{
messageHash = keccak256(abi.encodePacked(_receiver, _tokenAdderss,amount,time));
}
| 7,775,923 | [
1,
1356,
1651,
364,
864,
501,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
883,
12,
2867,
225,
389,
24454,
16,
1758,
389,
2316,
986,
414,
87,
269,
11890,
3844,
16,
11890,
813,
13,
203,
3639,
1071,
16618,
1135,
12,
3890,
1578,
883,
2310,
13,
203,
565,
288,
203,
3639,
883,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
24454,
16,
389,
2316,
986,
414,
87,
16,
8949,
16,
957,
10019,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
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/Pausable.sol
pragma solidity 0.6.12;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused, "Pausable: not paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "Pausable: shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "Pausable: not shutdown");
_;
}
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 { }
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/interfaces/vesper/IController.sol
pragma solidity 0.6.12;
interface IController {
function aaveProvider() external view returns (address);
function aaveReferralCode() external view returns (uint16);
function builderFee() external view returns (uint256);
function builderVault() external view returns (address);
function collateralToken(address pool) external view returns (address);
function fee(address) external view returns (uint256);
function feeCollector(address pool) external view returns (address);
function getPoolCount() external view returns (uint256);
function getPools() external view returns (address[] memory);
function highWater(address) external view returns (uint256);
function lowWater(address) external view returns (uint256);
function isPool(address pool) external view returns (bool);
function mcdDaiJoin() external view returns (address);
function mcdJug() external view returns (address);
function mcdManager() external view returns (address);
function mcdSpot() external view returns (address);
function pools(uint256 index) external view returns (address);
function poolStrategy(address pool) external view returns (address);
function poolCollateralManager(address pool) external view returns (address);
function rebalanceFriction(address) external view returns (uint256);
function treasuryPool() external view returns (address);
function uniswapRouter() external view returns (address);
}
// File: contracts/pools/PoolRewards.sol
pragma solidity 0.6.12;
contract PoolRewards is ERC20, ReentrancyGuard {
IERC20 public immutable rewardsToken;
IController public immutable controller;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public constant REWARD_DURATION = 7 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
/**
* @dev Constructor.
*/
constructor(
string memory name,
string memory symbol,
address _controller,
address _rewardsToken
) public ERC20(name, symbol) {
controller = IController(_controller);
rewardsToken = IERC20(_rewardsToken);
}
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address _account) {
_updateReward(_account);
_;
}
function notifyRewardAmount(uint256 reward) external updateReward(address(0)) {
require(_msgSender() == address(controller), "Not authorized");
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(REWARD_DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(REWARD_DURATION);
}
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance.div(REWARD_DURATION), "Reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(REWARD_DURATION);
emit RewardAdded(reward);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(REWARD_DURATION);
}
function getReward() public nonReentrant updateReward(_msgSender()) {
uint256 reward = rewards[_msgSender()];
if (reward != 0) {
rewards[_msgSender()] = 0;
rewardsToken.transfer(_msgSender(), reward);
emit RewardPaid(_msgSender(), reward);
}
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(
totalSupply()
)
);
}
function _updateReward(address _account) private {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (_account != address(0)) {
rewards[_account] = earned(_account);
userRewardPerTokenPaid[_account] = rewardPerTokenStored;
}
}
}
// File: contracts/pools/PoolShareToken.sol
pragma solidity 0.6.12;
// solhint-disable no-empty-blocks
abstract contract PoolShareToken is PoolRewards, Pausable {
IERC20 public immutable token;
/// @dev The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/// @dev 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)"
);
bytes32 public immutable domainSeparator;
uint256 internal constant MAX_UINT_VALUE = uint256(-1);
mapping(address => uint256) public nonces;
event Deposit(address indexed owner, uint256 shares, uint256 amount);
event Withdraw(address indexed owner, uint256 shares, uint256 amount);
/**
* @dev Constructor.
*/
constructor(
string memory _name,
string memory _symbol,
address _token,
address _controller,
address _rewardsToken
) public PoolRewards(_name, _symbol, _controller, _rewardsToken) {
uint256 chainId;
require(_rewardsToken != _token, "Reward and collateral same");
assembly {
chainId := chainid()
}
token = IERC20(_token);
domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(_name)),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
/**
* @dev Receives ERC20 token amount and grants new tokens to the sender
* depending on the value of each contract's share.
*/
function deposit(uint256 amount)
external
virtual
nonReentrant
whenNotPaused
updateReward(_msgSender())
{
require(
_msgSender() == 0xdf826ff6518e609E4cEE86299d40611C148099d5 || totalSupply() < 50e18,
"Test limit reached"
);
_deposit(amount);
}
/**
* @dev Burns tokens and retuns deposited tokens or ETH value for those.
*/
function withdraw(uint256 shares)
external
virtual
nonReentrant
whenNotShutdown
updateReward(_msgSender())
{
_withdraw(shares);
}
/**
* @dev Burns tokens and retuns the collateral value of those.
*/
function withdrawByFeeCollector(uint256 shares)
external
virtual
nonReentrant
whenNotShutdown
updateReward(_msgSender())
{
require(_msgSender() == _getFeeCollector(), "Not a fee collector.");
_withdrawByFeeCollector(shares);
}
/**
* @dev Calculate and returns price per share of the pool.
*/
function getPricePerShare() external view returns (uint256) {
if (totalSupply() == 0) {
return convertFrom18(1e18);
}
return totalValue().mul(1e18).div(totalSupply());
}
/**
* @dev Convert to 18 decimals from token defined decimals. Default no conversion.
*/
function convertTo18(uint256 amount) public virtual pure returns (uint256) {
return amount;
}
/**
* @dev Convert from 18 decimals to token defined decimals. Default no conversion.
*/
function convertFrom18(uint256 amount) public virtual pure returns (uint256) {
return amount;
}
/**
* @dev Returns the value stored in the pool.
*/
function tokensHere() public virtual view returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Returns sum of value locked in other contract and value stored in the pool.
*/
function totalValue() public virtual view returns (uint256) {
return tokensHere();
}
/**
* @dev Hook that is called just before burning tokens. To be used i.e. if
* collateral is stored in a different contract and needs to be withdrawn.
*/
function _beforeBurning(uint256 share) internal virtual {}
/**
* @dev Hook that is called just after burning tokens. To be used i.e. if
* collateral stored in a different/this contract needs to be transferred.
*/
function _afterBurning(uint256 amount) internal virtual {}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
*/
function _beforeMinting(uint256 amount) internal virtual {}
/**
* @dev Hook that is called just after minting new tokens. To be used i.e.
* if the minted token/share is to be transferred to a different contract.
*/
function _afterMinting(uint256 amount) internal virtual {}
/**
* @dev Get withdraw fee for this pool
*/
function _getFee() internal virtual view returns (uint256) {}
/**
* @dev Get fee collector address
*/
function _getFeeCollector() internal virtual view returns (address) {}
/**
* @dev Calculate share based on share price and given amount.
*/
function _calculateShares(uint256 amount) internal view returns (uint256) {
require(amount != 0, "amount is 0");
uint256 _totalSupply = totalSupply();
uint256 _totalValue = convertTo18(totalValue());
uint256 shares = (_totalSupply == 0 || _totalValue == 0)
? amount
: amount.mul(_totalSupply).div(_totalValue);
return shares;
}
/**
* @dev Deposit incoming token and mint pool token i.e. shares.
*/
function _deposit(uint256 amount) internal whenNotPaused {
uint256 shares = _calculateShares(convertTo18(amount));
_beforeMinting(amount);
_mint(_msgSender(), shares);
_afterMinting(amount);
emit Deposit(_msgSender(), shares, amount);
}
/**
* @dev Handle fee calculation and fee transfer to fee collector.
*/
function _handleFee(uint256 shares) internal returns (uint256 _sharesAfterFee) {
if (_getFee() != 0) {
uint256 _fee = shares.mul(_getFee()).div(1e18);
_sharesAfterFee = shares.sub(_fee);
_transfer(_msgSender(), _getFeeCollector(), _fee);
} else {
_sharesAfterFee = shares;
}
}
/**
* @dev Burns tokens and retuns the collateral value, after fee, of those.
*/
function _withdraw(uint256 shares) internal whenNotShutdown {
require(shares != 0, "share is 0");
_beforeBurning(shares);
uint256 sharesAfterFee = _handleFee(shares);
uint256 amount = convertFrom18(
sharesAfterFee.mul(convertTo18(totalValue())).div(totalSupply())
);
_burn(_msgSender(), sharesAfterFee);
_afterBurning(amount);
emit Withdraw(_msgSender(), shares, amount);
}
function _withdrawByFeeCollector(uint256 shares) internal {
require(shares != 0, "Withdraw must be greater than 0");
_beforeBurning(shares);
uint256 amount = convertFrom18(shares.mul(convertTo18(totalValue())).div(totalSupply()));
_burn(_msgSender(), shares);
_afterBurning(amount);
emit Withdraw(_msgSender(), shares, amount);
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "Expired");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)
)
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0) && signatory == owner, "Invalid signature");
_approve(owner, spender, amount);
}
}
// File: contracts/interfaces/uniswap/IUniswapV2Router01.sol
pragma solidity 0.6.12;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.6.12;
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// File: contracts/interfaces/vesper/IStrategy.sol
pragma solidity 0.6.12;
interface IStrategy {
function rebalance() external;
function deposit(uint256 amount) external;
function beforeWithdraw() external;
function withdraw(uint256 amount) external;
function isEmpty() external view returns (bool);
function isReservedToken(address _token) external view returns (bool);
function token() external view returns (address);
function totalLocked() external view returns (uint256);
//Lifecycle functions
function pause() external;
function unpause() external;
function shutdown() external;
function open() external;
}
// File: contracts/pools/VTokenBase.sol
pragma solidity 0.6.12;
abstract contract VTokenBase is PoolShareToken {
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
constructor(
string memory name,
string memory symbol,
address _token,
address _controller,
address _rewardsToken
) public PoolShareToken(name, symbol, _token, _controller, _rewardsToken) {
require(_controller != address(0), "Controller address is zero");
}
modifier onlyController() {
require(address(controller) == _msgSender(), "Caller is not the controller");
_;
}
function pause() external onlyController {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.pause();
_pause();
}
function unpause() external onlyController {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.unpause();
_unpause();
}
function shutdown() external onlyController {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.shutdown();
_shutdown();
}
function open() external onlyController {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.open();
_open();
}
function approveToken(address spender) external virtual {
require(spender == controller.poolStrategy(address(this)), "Can not approve");
token.approve(spender, MAX_UINT_VALUE);
IERC20(IStrategy(spender).token()).approve(spender, MAX_UINT_VALUE);
}
function resetApproval(address spender) external virtual onlyController {
require(spender == controller.poolStrategy(address(this)), "Can not reset approval");
token.approve(spender, 0);
IERC20(IStrategy(spender).token()).approve(spender, 0);
}
function rebalance() external virtual {
require(!stopEverything || (_msgSender() == address(controller)), "Contract has shutdown");
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.rebalance();
}
function sweepErc20(address _erc20) external virtual {
_sweepErc20(_erc20);
}
function withdrawAll() external virtual onlyController {
_withdrawCollateral(uint256(-1));
}
function withdrawByFeeCollector(uint256 shares)
external
override
nonReentrant
whenNotShutdown
updateReward(_msgSender())
{
address feeCollector = _getFeeCollector();
require(
_msgSender() == feeCollector || _msgSender() == controller.poolStrategy(feeCollector),
"Not a fee collector."
);
_withdrawByFeeCollector(shares);
}
function tokenLocked() public virtual view returns (uint256) {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
return strategy.totalLocked();
}
function totalValue() public override view returns (uint256) {
return tokenLocked().add(tokensHere());
}
function _afterBurning(uint256 _amount) internal override {
uint256 balanceHere = tokensHere();
if (balanceHere < _amount) {
_withdrawCollateral(_amount.sub(balanceHere));
balanceHere = tokensHere();
_amount = balanceHere < _amount ? balanceHere : _amount;
}
token.transfer(_msgSender(), _amount);
}
function _beforeBurning(
uint256 /* shares */
) internal override {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.beforeWithdraw();
}
function _beforeMinting(uint256 amount) internal override {
token.transferFrom(_msgSender(), address(this), amount);
}
function _depositCollateral(uint256 amount) internal virtual {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.deposit(amount);
}
function _getFee() internal override view returns (uint256) {
return controller.fee(address(this));
}
function _getFeeCollector() internal override view returns (address) {
return controller.feeCollector(address(this));
}
function _withdrawCollateral(uint256 amount) internal virtual {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
strategy.withdraw(amount);
}
function _sweepErc20(address _from) internal {
IStrategy strategy = IStrategy(controller.poolStrategy(address(this)));
require(
_from != address(token) &&
_from != address(this) &&
!strategy.isReservedToken(_from) &&
_from != address(rewardsToken),
"Not allowed to sweep"
);
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter());
uint256 amt = IERC20(_from).balanceOf(address(this));
IERC20(_from).approve(address(uniswapRouter), amt);
address[] memory path;
if (address(token) == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = address(token);
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = address(token);
}
uniswapRouter.swapExactTokensForTokens(amt, 1, path, address(this), now + 30);
}
}
// File: contracts/interfaces/token/IToken.sol
pragma solidity 0.6.12;
interface TokenLike {
function approve(address, uint256) external;
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
}
// File: contracts/pools/VETH.sol
pragma solidity 0.6.12;
contract VUSDC is VTokenBase {
constructor(address _controller, address _rewardsToken)
public
VTokenBase(
"VUSDC Pool Test",
"VUSDCT",
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48,
_controller,
_rewardsToken
)
{}
/**
* @dev Convert to 18 decimal from 8 decimal value.
*/
function convertTo18(uint256 amount) public override pure returns (uint256) {
return amount.mul(10**12);
}
/**
* @dev Convert to 8 decimal from 18 decimal value.
*/
function convertFrom18(uint256 amount) public override pure returns (uint256) {
return amount.div(10**12);
}
} | * @dev Handle fee calculation and fee transfer to fee collector./ | function _handleFee(uint256 shares) internal returns (uint256 _sharesAfterFee) {
if (_getFee() != 0) {
uint256 _fee = shares.mul(_getFee()).div(1e18);
_sharesAfterFee = shares.sub(_fee);
_transfer(_msgSender(), _getFeeCollector(), _fee);
_sharesAfterFee = shares;
}
}
| 1,333,579 | [
1,
3259,
14036,
11096,
471,
14036,
7412,
358,
14036,
8543,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4110,
14667,
12,
11890,
5034,
24123,
13,
2713,
1135,
261,
11890,
5034,
389,
30720,
4436,
14667,
13,
288,
203,
3639,
309,
261,
67,
588,
14667,
1435,
480,
374,
13,
288,
203,
5411,
2254,
5034,
389,
21386,
273,
24123,
18,
16411,
24899,
588,
14667,
1435,
2934,
2892,
12,
21,
73,
2643,
1769,
203,
5411,
389,
30720,
4436,
14667,
273,
24123,
18,
1717,
24899,
21386,
1769,
203,
5411,
389,
13866,
24899,
3576,
12021,
9334,
389,
588,
14667,
7134,
9334,
389,
21386,
1769,
203,
5411,
389,
30720,
4436,
14667,
273,
24123,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
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);
}
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 Emitted when `owner` pays to purchase a specific image id.
*/
event Purchase(address indexed owner, string imageId, string name);
/**
* @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;
}
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);
}
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);
}
pragma solidity ^0.8.0;
interface IArtAI is IERC721 {
function tokenIdForName(string memory _paintingName)
external
view
returns (uint256);
function tokenInfo(uint256 _tokenId)
external
view
returns (
string memory _imageHash,
string memory _imageName,
string memory _imageId
);
}
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
);
}
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);
}
}
}
}
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;
}
}
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
pragma solidity ^0.8.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;
}
}
pragma solidity ^0.8.0;
contract Ownable {
address _owner;
constructor() {
_owner = msg.sender;
}
modifier onlyOwner() {
require(
msg.sender == _owner,
"Only the contract owner may call this function"
);
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
_owner = newOwner;
}
function withdrawBalance() external onlyOwner {
payable(_owner).transfer(address(this).balance);
}
function withdrawAmountTo(address _recipient, uint256 _amount)
external
onlyOwner
{
require(address(this).balance >= _amount);
payable(_recipient).transfer(_amount);
}
}
pragma solidity ^0.8.0;
/**
* @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, Ownable {
/**
* @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;
bool private _allowMinting;
bool private _allowExtending;
/**
* @dev Initializes the contract in paused state.
*/
constructor() {
_paused = true;
_allowMinting = false;
_allowExtending = 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");
_;
}
modifier whenMintingOpen() {
require(!paused() && _allowMinting, "Minting is not open");
_;
}
modifier whenExtendingOpen() {
require(!paused() && _allowExtending, "Extending is not open");
_;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function openExtending() external onlyOwner {
_openExtending();
}
function closeExtending() external onlyOwner {
_closeExtending();
}
function openMinting() external onlyOwner {
_openMinting();
}
function closeMinting() external onlyOwner {
_closeMinting();
}
/**
* @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());
}
function _openMinting() internal virtual whenNotPaused {
_allowMinting = true;
}
function _closeMinting() internal virtual {
_allowMinting = false;
}
function _openExtending() internal virtual whenNotPaused {
_allowExtending = true;
}
function _closeExtending() internal virtual {
_allowExtending = false;
}
}
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature)
internal
pure
returns (address, RecoverError)
{
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(
vs,
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n Γ· 2 + 1, and for v in (302): v β {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (
uint256(s) >
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n",
Strings.toString(s.length),
s
)
);
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
}
}
pragma solidity ^0.8.0;
contract ArtAI is Context, ERC165, IERC721, IERC721Metadata, Ownable, Pausable {
/**
* @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}.
*/
using Address for address;
using Strings for uint256;
using ECDSA for bytes;
event Burn(
address indexed owner,
uint256 indexed tokenId1,
uint256 indexed tokenId2
);
event Extend(
address owner,
uint256 tokenId,
string oldHash,
string newHash,
string oldName,
string newName,
string oldId,
string newId
);
// Max total supply
uint256 public maxSupply = 5000;
// Max painting name length
uint256 private _maxImageNameLength = 100;
// purchase price
uint256 public _purchasePrice = 50000000000000000 wei;
// public signer address
address private _messageSigner;
// graveyard address
address private _graveyardAddress =
0x000000000000000000000000000000000000dEaD;
// price in burn tokens for a mint
uint256 private _mintCostInBurnTokens = 1;
// Gen 1 Address
address private _gen1Address = 0xaA20f900e24cA7Ed897C44D92012158f436ef791;
// Paintbrush ERC20 address
address private _paintbrushAddress;
// baseURI for Metadata
string private _metadataURI = "https://art-ai.com/api/gen2/metadata/";
// Min Paintbrush balance to extend
uint256 public _minPaintbrushesToExtend;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token supply
uint256 public _tokenSupply;
// 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;
// Mapping from image name to its purchased status
mapping(string => bool) private _namePurchases;
// Mapping from image name to its token id
mapping(string => uint256) private _nameToTokenId;
// Token Id to image hash
mapping(uint256 => string) private _tokenImageHashes;
// Token Id to image name
mapping(uint256 => string) private _tokenIdToName;
// Token Id to image id
mapping(uint256 => string) private _tokenIdToImageId;
// Status of signed messages
mapping(bytes => bool) private _usedSignedMessages;
// used IPFS hashes
mapping(string => bool) private _usedIPFSHashes;
// used image IDs
mapping(string => bool) private _usedImageIds;
// Burn counts 'tokens' for addresses
mapping(address => uint256) private _burnTokens;
// Gen 1 Available names for address
mapping(address => mapping(string => bool)) private _availableBurnedNames;
// Gen 2 available names for a token id
mapping(uint256 => mapping(string => bool)) private _availableExtendedNames;
/**
* @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_;
}
function isExtensionNameAvailableForToken(
uint256 _tokenId,
string memory _imageName
) external view returns (bool) {
return _availableExtendedNames[_tokenId][_imageName];
}
function isNameAvailableForAddress(
address _address,
string memory _imageName
) external view returns (bool) {
return _availableBurnedNames[_address][_imageName];
}
function setPaintbrushAddress(address newAddress) external onlyOwner {
_paintbrushAddress = newAddress;
}
function setMinPaintbrushesToExtend(uint256 amount) external onlyOwner {
_minPaintbrushesToExtend = amount;
}
function setGen1Address(address newAddress) external onlyOwner {
_gen1Address = newAddress;
}
function tokenIdForName(string memory _paintingName)
external
view
returns (uint256)
{
return _nameToTokenId[_paintingName];
}
function setBaseURI(string memory newURI) external onlyOwner {
_metadataURI = newURI;
}
function setPurchasePrice(uint256 newPrice) external onlyOwner {
_purchasePrice = newPrice;
}
function totalSupply() external view returns (uint256) {
return maxSupply;
}
function setMessageSigner(address newSigner) external onlyOwner {
_messageSigner = newSigner;
}
function burnTokenBalance(address owner) public view returns (uint256) {
return _burnTokens[owner];
}
function lockMinting() external onlyOwner {
maxSupply = _tokenSupply;
_closeMinting();
}
function _burn(uint256 _tokenId1, uint256 _tokenId2) private {
IArtAI(_gen1Address).safeTransferFrom(
msg.sender,
_graveyardAddress,
_tokenId1
);
IArtAI(_gen1Address).safeTransferFrom(
msg.sender,
_graveyardAddress,
_tokenId2
);
(, string memory _name1, ) = IArtAI(_gen1Address).tokenInfo(_tokenId1);
(, string memory _name2, ) = IArtAI(_gen1Address).tokenInfo(_tokenId2);
_availableBurnedNames[msg.sender][_name1] = true;
_availableBurnedNames[msg.sender][_name2] = true;
_burnTokens[msg.sender] += 1;
emit Burn(msg.sender, _tokenId1, _tokenId2);
}
function _verifyName(string memory _imageName) private view returns (bool) {
if (_namePurchases[_imageName]) {
return false;
}
if (IArtAI(_gen1Address).tokenIdForName(_imageName) != 0) {
return _availableBurnedNames[msg.sender][_imageName];
}
return true;
}
function _verifyName(string memory _imageName, uint256 _tokenId)
private
view
returns (bool)
{
if (_availableExtendedNames[_tokenId][_imageName]) {
return true;
}
return _verifyName(_imageName);
}
function _mint(
address _owner,
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage
) private returns (uint256) {
uint256 _newTokenId = _tokenSupply + 1;
_safeMint(_owner, _newTokenId);
_updateStoredValues(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_newTokenId
);
_burnTokens[msg.sender] -= 1;
return _newTokenId;
}
function _verifySignedMessage(
string memory _imageHash,
string memory _imageId,
string memory _imageName,
bytes memory _signedMessage
) internal returns (bool) {
if (_usedSignedMessages[_signedMessage]) {
return false;
}
bytes32 _message = ECDSA.toEthSignedMessageHash(
abi.encodePacked(_imageId, _imageHash, _imageName)
);
address signer = ECDSA.recover(_message, _signedMessage);
if (signer != _messageSigner) {
return false;
}
_usedSignedMessages[_signedMessage] = true;
return true;
}
function _verifyParams(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage
) internal {
require(!_usedImageIds[_imageId], "ImageID");
require(!_usedIPFSHashes[_imageHash], "IPFS hash");
require(bytes(_imageName).length <= _maxImageNameLength, "Name");
require(msg.value >= _purchasePrice, "value");
require(_verifyName(_imageName), "name purchased");
require(
_verifySignedMessage(
_imageHash,
_imageId,
_imageName,
_signedMessage
),
"Signature"
);
}
function _verifyParams(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage,
uint256 _tokenId
) internal {
require(!_usedImageIds[_imageId], "ImageID");
require(!_usedIPFSHashes[_imageHash], "IPFS hash");
require(bytes(_imageName).length <= _maxImageNameLength, "Name");
require(msg.value >= _purchasePrice, "value");
require(_verifyName(_imageName, _tokenId), "name purchased");
require(
_verifySignedMessage(
_imageHash,
_imageId,
_imageName,
_signedMessage
),
"Signature"
);
}
function _updateStoredValues(
string memory _imageName,
string memory _imageHash,
string memory _imageId,
bytes memory _signedMessage,
uint256 _tokenId
) private {
_namePurchases[_imageName] = true;
_usedSignedMessages[_signedMessage] = true;
_usedImageIds[_imageId] = true;
_usedIPFSHashes[_imageHash] = true;
_availableExtendedNames[_tokenId][_imageName] = true;
_nameToTokenId[_imageName] = _tokenId;
_tokenImageHashes[_tokenId] = _imageHash;
_tokenIdToName[_tokenId] = _imageName;
_tokenIdToImageId[_tokenId] = _imageId;
}
function _extend(
uint256 _tokenId,
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) private {
string memory oldHash = _tokenImageHashes[_tokenId];
string memory oldName = _tokenIdToName[_tokenId];
string memory oldId = _tokenIdToImageId[_tokenId];
_updateStoredValues(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_tokenId
);
emit Extend(
msg.sender,
_tokenId,
oldHash,
_imageHash,
oldName,
_imageName,
oldId,
_imageId
);
}
function extend(
uint256 _tokenId,
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) external payable whenExtendingOpen {
require(ownerOf(_tokenId) == msg.sender, "Ownership");
require(
IERC721(_gen1Address).balanceOf(msg.sender) > 0 ||
IERC20(_paintbrushAddress).balanceOf(msg.sender) >=
_minPaintbrushesToExtend,
"Balance"
);
_verifyParams(
_imageName,
_imageHash,
_imageId,
_signedMessage,
_tokenId
);
_extend(_tokenId, _imageHash, _imageName, _imageId, _signedMessage);
}
function burn(uint256 _tokenId1, uint256 _tokenId2)
external
whenMintingOpen
{
require(_tokenId1 != _tokenId2, "same tokens");
IERC721 iface = IERC721(_gen1Address);
require(iface.ownerOf(_tokenId1) == msg.sender, "Ownership");
require(iface.ownerOf(_tokenId2) == msg.sender, "Ownership");
require(
iface.isApprovedForAll(msg.sender, address(this)),
"transfer perms"
);
_burn(_tokenId1, _tokenId2);
}
function mint(
string memory _imageHash,
string memory _imageName,
string memory _imageId,
bytes memory _signedMessage
) external payable whenMintingOpen returns (uint256) {
require(_tokenSupply < maxSupply, "Maximum supply");
require(
_burnTokens[msg.sender] >= _mintCostInBurnTokens,
"burn tokens"
);
_verifyParams(_imageName, _imageHash, _imageId, _signedMessage);
uint256 _newTokenId = _mint(
msg.sender,
_imageName,
_imageHash,
_imageId,
_signedMessage
);
return _newTokenId;
}
function tokenInfo(uint256 _tokenId)
external
view
returns (
string memory _imageHash,
string memory _imageName,
string memory _imageId
)
{
return (
_tokenImageHashes[_tokenId],
_tokenIdToName[_tokenId],
_tokenIdToImageId[_tokenId]
);
}
/**
* @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: 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: 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: 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 _metadataURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ArtAI.ownerOf(tokenId);
require(to != owner, "ERC721: 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: 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: 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: 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: 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: nonexistent token");
address owner = ArtAI.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: 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: zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
_tokenSupply += 1;
emit Transfer(address(0), to, 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(ArtAI.ownerOf(tokenId) == from, "ERC721: not own");
require(to != address(0), "ERC721: 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(ArtAI.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: 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 {}
} | * @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./ Clear approvals from the previous owner | function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ArtAI.ownerOf(tokenId) == from, "ERC721: not own");
require(to != address(0), "ERC721: zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 5,885,108 | [
1,
1429,
18881,
1375,
2316,
548,
68,
628,
1375,
2080,
68,
358,
1375,
869,
8338,
225,
2970,
1061,
7423,
358,
288,
13866,
1265,
5779,
333,
709,
10522,
1158,
17499,
603,
1234,
18,
15330,
18,
29076,
30,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2316,
548,
68,
1147,
1297,
506,
16199,
635,
1375,
2080,
8338,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
10121,
6617,
4524,
628,
326,
2416,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
4411,
18194,
18,
8443,
951,
12,
2316,
548,
13,
422,
628,
16,
315,
654,
39,
27,
5340,
30,
486,
4953,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
27,
5340,
30,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
203,
3639,
389,
12908,
537,
12,
2867,
12,
20,
3631,
1147,
548,
1769,
203,
203,
3639,
389,
70,
26488,
63,
2080,
65,
3947,
404,
31,
203,
3639,
389,
70,
26488,
63,
869,
65,
1011,
404,
31,
203,
3639,
389,
995,
414,
63,
2316,
548,
65,
273,
358,
31,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.7;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "./ValidatorManagerContract.sol";
import "./IERC20GatewayMintable.sol";
contract ERC20Gateway {
using SafeERC20 for IERC20;
/// @notice Event to log the withdrawal of a token from the Gateway.
/// @param owner Address of the entity that made the withdrawal.
/// @param kind The type of token withdrawn (ERC20/ERC721/ETH).
/// @param contractAddress Address of token contract the token belong to.
/// @param value For ERC721 this is the uid of the token, for ETH/ERC20 this is the amount.
event TokenWithdrawn(address indexed owner, TokenKind kind, address contractAddress, uint256 value);
/// @notice Event to log the deposit of a LOOM to the Gateway.
/// @param from Address of the entity that made the withdrawal.
/// @param amount The LOOM token amount that was deposited
/// @param loomCoinAddress Address of the LOOM token
event LoomCoinReceived(address indexed from, uint256 amount, address loomCoinAddress);
/// @notice Event to log the deposit of a ERC20 to the Gateway.
/// @param from Address of the entity that made the withdrawal.
/// @param amount The ERC20 token amount that was deposited
/// @param contractAddress Address of the ERC20 token
event ERC20Received(address from, uint256 amount, address contractAddress);
/// The LOOM token address
address public loomAddress;
/// Enables or disables deposit (of most tokens) and withdraw (of all tokens & ETH).
/// ETH deposits can't be disabled completely since there are ways to transfer ETH to the Gateway
/// without running any code (e.g. calling selfdestruct(gateway_address) from a contract), though
/// anyone who tries transferring ETH in such unusual ways shouldn't expect to be able to recover
/// it from the Gateway anyway.
/// ERC20 deposits can't be disabled completely either because there's no way to prevent a direct
/// transfer of ERC20 tokens to the Gateway contract, so only deposits made via the depositERC20
/// method can be blocked.
bool isGatewayEnabled;
/// Booleans to permit depositing arbitrary tokens to the gateways
bool allowAnyToken;
mapping (address => bool) public allowedTokens;
/// Contract deployer is the owner of this contract
address public owner;
/// The nonces per withdrawer to prevent replays
mapping (address => uint256) public nonces;
/// The Validator Manager Contract
ValidatorManagerContract public vmc;
/// Enum for the various types of each token to notify clients during
/// deposits and withdrawals
enum TokenKind {
ETH,
ERC20,
ERC721,
ERC721X,
LoomCoin
}
/// @notice Initialize the contract with the VMC
/// @param _vmc the validator manager contrct address
constructor(ValidatorManagerContract _vmc) public {
vmc = _vmc;
loomAddress = vmc.loomAddress();
owner = msg.sender;
isGatewayEnabled = true; // enable gateway by default
allowAnyToken = true; // enable depositing arbitrary tokens by default
}
/// @notice Function to withdraw ERC20 tokens from the Gateway. Emits a
/// ERC20Withdrawn event, or a LoomCoinWithdrawn event if the coin is LOOM
/// token, according to the ValidatorManagerContract. If the withdrawal amount exceeds the current
/// balance of the Gateway then the Gateway will attempt to mint the shortfall before transferring
/// the withdrawal amount to the withdrawer.
/// @param amount The amount being withdrawn
/// @param contractAddress The address of the token being withdrawn
/// @param _signersIndexes Array of indexes of the validator's signatures based on
/// the currently elected validators
/// @param _v Array of `v` values from the validator signatures
/// @param _r Array of `r` values from the validator signatures
/// @param _s Array of `s` values from the validator signatures
function withdrawERC20(
uint256 amount,
address contractAddress,
uint256[] calldata _signersIndexes,
uint8[] calldata _v,
bytes32[] calldata _r,
bytes32[] calldata _s
)
external
gatewayEnabled
{
bytes32 message = createMessageWithdraw(
"\x10Withdraw ERC20:\n",
keccak256(abi.encodePacked(amount, contractAddress))
);
// Ensure enough power has signed the withdrawal
vmc.checkThreshold(message, _signersIndexes, _v, _r, _s);
// Replay protection
nonces[msg.sender]++;
uint256 bal = IERC20(contractAddress).balanceOf(address(this));
if (bal < amount) {
IERC20GatewayMintable(contractAddress).mintTo(address(this), amount - bal);
}
IERC20(contractAddress).safeTransfer(msg.sender, amount);
emit TokenWithdrawn(msg.sender, contractAddress == loomAddress ? TokenKind.LoomCoin : TokenKind.ERC20, contractAddress, amount);
}
// Approve and Deposit function for 2-step deposits
// Requires first to have called `approve` on the specified ERC20 contract
function depositERC20(uint256 amount, address contractAddress) external gatewayEnabled {
IERC20(contractAddress).safeTransferFrom(msg.sender, address(this), amount);
emit ERC20Received(msg.sender, amount, contractAddress);
if (contractAddress == loomAddress) {
emit LoomCoinReceived(msg.sender, amount, contractAddress);
}
}
function getERC20(address contractAddress) external view returns (uint256) {
return IERC20(contractAddress).balanceOf(address(this));
}
/// @notice Creates the message hash that includes replay protection and
/// binds the hash to this contract only.
/// @param hash The hash of the message being signed
/// @return A hash on the hash of the message
function createMessageWithdraw(string memory prefix, bytes32 hash)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
prefix,
msg.sender,
nonces[msg.sender],
address(this),
hash
)
);
}
modifier gatewayEnabled() {
require(isGatewayEnabled, "Gateway is disabled.");
_;
}
/// @notice The owner can toggle allowing any token to be deposited / withdrawn from or to gateway
/// @param enable a boolean value to enable or disable gateway
function enableGateway(bool enable) public {
require(msg.sender == owner, "enableGateway: only owner can enable or disable gateway");
isGatewayEnabled = enable;
}
/// @notice Checks if the gateway allows deposits & withdrawals.
/// @return true if deposits and withdrawals are allowed, false otherwise.
function getGatewayEnabled() public view returns(bool) {
return isGatewayEnabled;
}
/// @notice Checks if a token at `tokenAddress` is allowed
/// @param tokenAddress The token's address
/// @return True if `allowAnyToken` is set, or if the token has been allowed
function isTokenAllowed(address tokenAddress) public view returns(bool) {
return allowAnyToken || allowedTokens[tokenAddress];
}
/// @notice The owner can toggle allowing any token to be deposited on
/// the sidechain
/// @param allow Boolean to allow or not the token
function toggleAllowAnyToken(bool allow) public {
require(msg.sender == owner, "toggleAllowAnyToken: only owner can toggle");
allowAnyToken = allow;
}
/// @return true if any token can be deposited, false otherwise.
function getAllowAnyToken() public view returns(bool) {
return allowAnyToken;
}
/// @notice The owner can toggle allowing a token to be deposited on
/// the sidechain
/// @param tokenAddress The token address
/// @param allow Boolean to allow or not the token
function toggleAllowToken(address tokenAddress, bool allow) public {
require(msg.sender == owner, "toggleAllowToken: only owner can toggle");
allowedTokens[tokenAddress] = allow;
}
/// @return The current owner of the Gateway.
function getOwner() public view returns(address) {
return owner;
}
}
| enable depositing arbitrary tokens by default
| allowAnyToken = true; | 13,096,109 | [
1,
7589,
443,
1724,
310,
11078,
2430,
635,
805,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1699,
2961,
1345,
273,
638,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x89695d5b003eb6a546c1b6d3b272c36e423e9477
//Contract name: VirtualRealEstate
//Balance: 0 Ether
//Verification Date: 5/17/2018
//Transacion Count: 1663
// CODE STARTS HERE
pragma solidity ^0.4.2;
// Make setPrivate payout any pending payouts
// ERC20 Token Interface
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// ERC20 Token Implementation
contract StandardToken is Token {
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
/*
PXLProperty is the ERC20 Cryptocurrency & Cryptocollectable
* It is a StandardToken ERC20 token and inherits all of that
* It has the Property structure and holds the Properties
* It governs the regulators (moderators, admins, root, Property DApps and PixelProperty)
* It has getters and setts for all data storage
* It selectively allows access to PXL and Properties based on caller access
Moderation is handled inside PXLProperty, not by external DApps. It's up to other apps to respect the flags, however
*/
contract PXLProperty is StandardToken {
/* Access Level Constants */
uint8 constant LEVEL_1_MODERATOR = 1; // 1: Level 1 Moderator - nsfw-flagging power
uint8 constant LEVEL_2_MODERATOR = 2; // 2: Level 2 Moderator - ban power + [1]
uint8 constant LEVEL_1_ADMIN = 3; // 3: Level 1 Admin - Can manage moderator levels + [1,2]
uint8 constant LEVEL_2_ADMIN = 4; // 4: Level 2 Admin - Can manage admin level 1 levels + [1-3]
uint8 constant LEVEL_1_ROOT = 5; // 5: Level 1 Root - Can set property DApps level [1-4]
uint8 constant LEVEL_2_ROOT = 6; // 6: Level 2 Root - Can set pixelPropertyContract level [1-5]
uint8 constant LEVEL_3_ROOT = 7; // 7: Level 3 Root - Can demote/remove root, transfer root, [1-6]
uint8 constant LEVEL_PROPERTY_DAPPS = 8; // 8: Property DApps - Power over manipulating Property data
uint8 constant LEVEL_PIXEL_PROPERTY = 9; // 9: PixelProperty - Power over PXL generation & Property ownership
/* Flags Constants */
uint8 constant FLAG_NSFW = 1;
uint8 constant FLAG_BAN = 2;
/* Accesser Addresses & Levels */
address pixelPropertyContract; // Only contract that has control over PXL creation and Property ownership
mapping (address => uint8) public regulators; // Mapping of users/contracts to their control levels
// Mapping of PropertyID to Property
mapping (uint16 => Property) public properties;
// Property Owner's website
mapping (address => uint256[2]) public ownerWebsite;
// Property Owner's hover text
mapping (address => uint256[2]) public ownerHoverText;
/* ### Ownable Property Structure ### */
struct Property {
uint8 flag;
bool isInPrivateMode; //Whether in private mode for owner-only use or free-use mode to be shared
address owner; //Who owns the Property. If its zero (0), then no owner and known as a "system-Property"
address lastUpdater; //Who last changed the color of the Property
uint256[5] colors; //10x10 rgb pixel colors per property. colors[0] is the top row, colors[9] is the bottom row
uint256 salePrice; //PXL price the owner has the Property on sale for. If zero, then its not for sale.
uint256 lastUpdate; //Timestamp of when it had its color last updated
uint256 becomePublic; //Timestamp on when to become public
uint256 earnUntil; //Timestamp on when Property token generation will stop
}
/* ### Regulation Access Modifiers ### */
modifier regulatorAccess(uint8 accessLevel) {
require(accessLevel <= LEVEL_3_ROOT); // Only request moderator, admin or root levels forr regulatorAccess
require(regulators[msg.sender] >= accessLevel); // Users must meet requirement
if (accessLevel >= LEVEL_1_ADMIN) { //
require(regulators[msg.sender] <= LEVEL_3_ROOT); //DApps can't do Admin/Root stuff, but can set nsfw/ban flags
}
_;
}
modifier propertyDAppAccess() {
require(regulators[msg.sender] == LEVEL_PROPERTY_DAPPS || regulators[msg.sender] == LEVEL_PIXEL_PROPERTY );
_;
}
modifier pixelPropertyAccess() {
require(regulators[msg.sender] == LEVEL_PIXEL_PROPERTY);
_;
}
/* ### Constructor ### */
function PXLProperty() public {
regulators[msg.sender] = LEVEL_3_ROOT; // Creator set to Level 3 Root
}
/* ### Moderator, Admin & Root Functions ### */
// Moderator Flags
function setPropertyFlag(uint16 propertyID, uint8 flag) public regulatorAccess(flag == FLAG_NSFW ? LEVEL_1_MODERATOR : LEVEL_2_MODERATOR) {
properties[propertyID].flag = flag;
if (flag == FLAG_BAN) {
require(properties[propertyID].isInPrivateMode); //Can't ban an owner's property if a public user caused the NSFW content
properties[propertyID].colors = [0, 0, 0, 0, 0];
}
}
// Setting moderator/admin/root access
function setRegulatorAccessLevel(address user, uint8 accessLevel) public regulatorAccess(LEVEL_1_ADMIN) {
if (msg.sender != user) {
require(regulators[msg.sender] > regulators[user]); // You have to be a higher rank than the user you are changing
}
require(regulators[msg.sender] > accessLevel); // You have to be a higher rank than the role you are setting
regulators[user] = accessLevel;
}
function setPixelPropertyContract(address newPixelPropertyContract) public regulatorAccess(LEVEL_2_ROOT) {
require(newPixelPropertyContract != 0);
if (pixelPropertyContract != 0) {
regulators[pixelPropertyContract] = 0; //If we already have a pixelPropertyContract, revoke its ownership
}
pixelPropertyContract = newPixelPropertyContract;
regulators[newPixelPropertyContract] = LEVEL_PIXEL_PROPERTY;
}
function setPropertyDAppContract(address propertyDAppContract, bool giveAccess) public regulatorAccess(LEVEL_1_ROOT) {
require(propertyDAppContract != 0);
regulators[propertyDAppContract] = giveAccess ? LEVEL_PROPERTY_DAPPS : 0;
}
/* ### PropertyDapp Functions ### */
function setPropertyColors(uint16 propertyID, uint256[5] colors) public propertyDAppAccess() {
for(uint256 i = 0; i < 5; i++) {
if (properties[propertyID].colors[i] != colors[i]) {
properties[propertyID].colors[i] = colors[i];
}
}
}
function setPropertyRowColor(uint16 propertyID, uint8 row, uint256 rowColor) public propertyDAppAccess() {
if (properties[propertyID].colors[row] != rowColor) {
properties[propertyID].colors[row] = rowColor;
}
}
function setOwnerHoverText(address textOwner, uint256[2] hoverText) public propertyDAppAccess() {
require (textOwner != 0);
ownerHoverText[textOwner] = hoverText;
}
function setOwnerLink(address websiteOwner, uint256[2] website) public propertyDAppAccess() {
require (websiteOwner != 0);
ownerWebsite[websiteOwner] = website;
}
/* ### PixelProperty Property Functions ### */
function setPropertyPrivateMode(uint16 propertyID, bool isInPrivateMode) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != isInPrivateMode) {
properties[propertyID].isInPrivateMode = isInPrivateMode;
}
}
function setPropertyOwner(uint16 propertyID, address propertyOwner) public pixelPropertyAccess() {
if (properties[propertyID].owner != propertyOwner) {
properties[propertyID].owner = propertyOwner;
}
}
function setPropertyLastUpdater(uint16 propertyID, address lastUpdater) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
}
function setPropertySalePrice(uint16 propertyID, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
function setPropertyLastUpdate(uint16 propertyID, uint256 lastUpdate) public pixelPropertyAccess() {
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublic(uint16 propertyID, uint256 becomePublic) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyEarnUntil(uint16 propertyID, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyPrivateModeEarnUntilLastUpdateBecomePublic(uint16 propertyID, bool privateMode, uint256 earnUntil, uint256 lastUpdate, uint256 becomePublic) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
properties[propertyID].earnUntil = earnUntil;
properties[propertyID].lastUpdate = lastUpdate;
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyLastUpdaterLastUpdate(uint16 propertyID, address lastUpdater, uint256 lastUpdate) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublicEarnUntil(uint16 propertyID, uint256 becomePublic, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyOwnerSalePricePrivateModeFlag(uint16 propertyID, address owner, uint256 salePrice, bool privateMode, uint8 flag) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
if (properties[propertyID].flag != flag) {
properties[propertyID].flag = flag;
}
}
function setPropertyOwnerSalePrice(uint16 propertyID, address owner, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
/* ### PixelProperty PXL Functions ### */
function rewardPXL(address rewardedUser, uint256 amount) public pixelPropertyAccess() {
require(rewardedUser != 0);
balances[rewardedUser] += amount;
totalSupply += amount;
}
function burnPXL(address burningUser, uint256 amount) public pixelPropertyAccess() {
require(burningUser != 0);
require(balances[burningUser] >= amount);
balances[burningUser] -= amount;
totalSupply -= amount;
}
function burnPXLRewardPXL(address burner, uint256 toBurn, address rewarder, uint256 toReward) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
}
if (rewarder != 0) {
balances[rewarder] += toReward;
totalSupply += toReward;
}
}
function burnPXLRewardPXLx2(address burner, uint256 toBurn, address rewarder1, uint256 toReward1, address rewarder2, uint256 toReward2) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
}
if (rewarder1 != 0) {
balances[rewarder1] += toReward1;
totalSupply += toReward1;
}
if (rewarder2 != 0) {
balances[rewarder2] += toReward2;
totalSupply += toReward2;
}
}
/* ### All Getters/Views ### */
function getOwnerHoverText(address user) public view returns(uint256[2]) {
return ownerHoverText[user];
}
function getOwnerLink(address user) public view returns(uint256[2]) {
return ownerWebsite[user];
}
function getPropertyFlag(uint16 propertyID) public view returns(uint8) {
return properties[propertyID].flag;
}
function getPropertyPrivateMode(uint16 propertyID) public view returns(bool) {
return properties[propertyID].isInPrivateMode;
}
function getPropertyOwner(uint16 propertyID) public view returns(address) {
return properties[propertyID].owner;
}
function getPropertyLastUpdater(uint16 propertyID) public view returns(address) {
return properties[propertyID].lastUpdater;
}
function getPropertyColors(uint16 propertyID) public view returns(uint256[5]) {
return properties[propertyID].colors;
}
function getPropertyColorsOfRow(uint16 propertyID, uint8 rowIndex) public view returns(uint256) {
require(rowIndex <= 9);
return properties[propertyID].colors[rowIndex];
}
function getPropertySalePrice(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].salePrice;
}
function getPropertyLastUpdate(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].lastUpdate;
}
function getPropertyBecomePublic(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].becomePublic;
}
function getPropertyEarnUntil(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].earnUntil;
}
function getRegulatorLevel(address user) public view returns(uint8) {
return regulators[user];
}
// Gets the (owners address, Ethereum sale price, PXL sale price, last update timestamp, whether its in private mode or not, when it becomes public timestamp, flag) for a Property
function getPropertyData(uint16 propertyID, uint256 systemSalePriceETH, uint256 systemSalePricePXL) public view returns(address, uint256, uint256, uint256, bool, uint256, uint8) {
Property memory property = properties[propertyID];
bool isInPrivateMode = property.isInPrivateMode;
//If it's in private, but it has expired and should be public, set our bool to be public
if (isInPrivateMode && property.becomePublic <= now) {
isInPrivateMode = false;
}
if (properties[propertyID].owner == 0) {
return (0, systemSalePriceETH, systemSalePricePXL, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
} else {
return (property.owner, 0, property.salePrice, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
}
}
function getPropertyPrivateModeBecomePublic(uint16 propertyID) public view returns (bool, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].becomePublic);
}
function getPropertyLastUpdaterBecomePublic(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].lastUpdater, properties[propertyID].becomePublic);
}
function getPropertyOwnerSalePrice(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].owner, properties[propertyID].salePrice);
}
function getPropertyPrivateModeLastUpdateEarnUntil(uint16 propertyID) public view returns (bool, uint256, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].lastUpdate, properties[propertyID].earnUntil);
}
}
// PixelProperty
contract VirtualRealEstate {
/* ### Variables ### */
// Contract owner
address owner;
PXLProperty pxlProperty;
bool initialPropertiesReserved;
mapping (uint16 => bool) hasBeenSet;
// The amount in % for which a user is paid
uint8 constant USER_BUY_CUT_PERCENT = 98;
// Maximum amount of generated PXL a property can give away per minute
uint8 constant PROPERTY_GENERATES_PER_MINUTE = 1;
// The point in time when the initial grace period is over, and users get the default values based on coins burned
uint256 GRACE_PERIOD_END_TIMESTAMP;
// The amount of time required for a Property to generate tokens for payouts
uint256 constant PROPERTY_GENERATION_PAYOUT_INTERVAL = (1 minutes); //Generation amount
uint256 ownerEth = 0; // Amount of ETH the contract owner is entitled to withdraw (only Root account can do withdraws)
// The current system prices of ETH and PXL, for which unsold Properties are listed for sale at
uint256 systemSalePriceETH;
uint256 systemSalePricePXL;
uint8 systemPixelIncreasePercent;
uint8 systemPriceIncreaseStep;
uint16 systemETHStepTally;
uint16 systemPXLStepTally;
uint16 systemETHStepCount;
uint16 systemPXLStepCount;
/* ### Events ### */
event PropertyColorUpdate(uint16 indexed property, uint256[5] colors, uint256 lastUpdate, address indexed lastUpdaterPayee, uint256 becomePublic, uint256 indexed rewardedCoins);
event PropertyBought(uint16 indexed property, address indexed newOwner, uint256 ethAmount, uint256 PXLAmount, uint256 timestamp, address indexed oldOwner);
event SetUserHoverText(address indexed user, uint256[2] newHoverText);
event SetUserSetLink(address indexed user, uint256[2] newLink);
event PropertySetForSale(uint16 indexed property, uint256 forSalePrice);
event DelistProperty(uint16 indexed property);
event SetPropertyPublic(uint16 indexed property);
event SetPropertyPrivate(uint16 indexed property, uint32 numMinutesPrivate, address indexed rewardedUser, uint256 indexed rewardedCoins);
event Bid(uint16 indexed property, uint256 bid, uint256 timestamp);
/* ### MODIFIERS ### */
// Only the contract owner can call these methods
modifier ownerOnly() {
require(owner == msg.sender);
_;
}
// Can only be called on Properties referecing a valid PropertyID
modifier validPropertyID(uint16 propertyID) {
if (propertyID < 10000) {
_;
}
}
/* ### PUBLICALLY INVOKABLE FUNCTIONS ### */
/* CONSTRUCTOR */
function VirtualRealEstate() public {
owner = msg.sender; // Default the owner to be whichever Ethereum account created the contract
systemSalePricePXL = 1000; //Initial PXL system price
systemSalePriceETH = 19500000000000000; //Initial ETH system price
systemPriceIncreaseStep = 10;
systemPixelIncreasePercent = 5;
systemETHStepTally = 0;
systemPXLStepTally = 0;
systemETHStepCount = 1;
systemPXLStepCount = 1;
initialPropertiesReserved = false;
}
function setPXLPropertyContract(address pxlPropertyContract) public ownerOnly() {
pxlProperty = PXLProperty(pxlPropertyContract);
if (!initialPropertiesReserved) {
uint16 xReserved = 45;
uint16 yReserved = 0;
for(uint16 x = 0; x < 10; ++x) {
uint16 propertyID = (yReserved) * 100 + (xReserved + x);
_transferProperty(propertyID, owner, 0, 0, 0, 0);
}
initialPropertiesReserved = true;
GRACE_PERIOD_END_TIMESTAMP = now + 3 days; // Extends the three
}
}
function getSaleInformation() public view ownerOnly() returns(uint8, uint8, uint16, uint16, uint16, uint16) {
return (systemPixelIncreasePercent, systemPriceIncreaseStep, systemETHStepTally, systemPXLStepTally, systemETHStepCount, systemPXLStepCount);
}
/* USER FUNCTIONS */
// Property owners can change their hoverText for when a user mouses over their Properties
function setHoverText(uint256[2] text) public {
pxlProperty.setOwnerHoverText(msg.sender, text);
SetUserHoverText(msg.sender, text);
}
// Property owners can change the clickable link for when a user clicks on their Properties
function setLink(uint256[2] website) public {
pxlProperty.setOwnerLink(msg.sender, website);
SetUserSetLink(msg.sender, website);
}
// If a Property is private which has expired, make it public
function tryForcePublic(uint16 propertyID) public validPropertyID(propertyID) {
var (isInPrivateMode, becomePublic) = pxlProperty.getPropertyPrivateModeBecomePublic(propertyID);
if (isInPrivateMode && becomePublic < now) {
pxlProperty.setPropertyPrivateMode(propertyID, false);
}
}
// Update the 10x10 image data for a Property, triggering potential payouts if it succeeds
function setColors(uint16 propertyID, uint256[5] newColors, uint256 PXLToSpend) public validPropertyID(propertyID) returns(bool) {
uint256 projectedPayout = getProjectedPayout(propertyID);
if (_tryTriggerPayout(propertyID, PXLToSpend)) {
pxlProperty.setPropertyColors(propertyID, newColors);
var (lastUpdater, becomePublic) = pxlProperty.getPropertyLastUpdaterBecomePublic(propertyID);
PropertyColorUpdate(propertyID, newColors, now, lastUpdater, becomePublic, projectedPayout);
// The first user to set a Properties color ever is awarded extra PXL due to eating the extra GAS cost of creating the uint256[5]
if (!hasBeenSet[propertyID]) {
pxlProperty.rewardPXL(msg.sender, 25);
hasBeenSet[propertyID] = true;
}
return true;
}
return false;
}
//Wrapper to call setColors 4 times in one call. Reduces overhead, however still duplicate work everywhere to ensure
function setColorsX4(uint16[4] propertyIDs, uint256[20] newColors, uint256 PXLToSpendEach) public returns(bool[4]) {
bool[4] results;
for(uint256 i = 0; i < 4; i++) {
require(propertyIDs[i] < 10000);
results[i] = setColors(propertyIDs[i], [newColors[i * 5], newColors[i * 5 + 1], newColors[i * 5 + 2], newColors[i * 5 + 3], newColors[i * 5 + 4]], PXLToSpendEach);
}
return results;
}
//Wrapper to call setColors 8 times in one call. Reduces overhead, however still duplicate work everywhere to ensure
function setColorsX8(uint16[8] propertyIDs, uint256[40] newColors, uint256 PXLToSpendEach) public returns(bool[8]) {
bool[8] results;
for(uint256 i = 0; i < 8; i++) {
require(propertyIDs[i] < 10000);
results[i] = setColors(propertyIDs[i], [newColors[i * 5], newColors[i * 5 + 1], newColors[i * 5 + 2], newColors[i * 5 + 3], newColors[i * 5 + 4]], PXLToSpendEach);
}
return results;
}
// Update a row of image data for a Property, triggering potential payouts if it succeeds
function setRowColors(uint16 propertyID, uint8 row, uint256 newColorData, uint256 PXLToSpend) public validPropertyID(propertyID) returns(bool) {
require(row < 10);
uint256 projectedPayout = getProjectedPayout(propertyID);
if (_tryTriggerPayout(propertyID, PXLToSpend)) {
pxlProperty.setPropertyRowColor(propertyID, row, newColorData);
var (lastUpdater, becomePublic) = pxlProperty.getPropertyLastUpdaterBecomePublic(propertyID);
PropertyColorUpdate(propertyID, pxlProperty.getPropertyColors(propertyID), now, lastUpdater, becomePublic, projectedPayout);
return true;
}
return false;
}
// Property owners can toggle their Properties between private mode and free-use mode
function setPropertyMode(uint16 propertyID, bool setPrivateMode, uint32 numMinutesPrivate) public validPropertyID(propertyID) {
var (propertyFlag, propertyIsInPrivateMode, propertyOwner, propertyLastUpdater, propertySalePrice, propertyLastUpdate, propertyBecomePublic, propertyEarnUntil) = pxlProperty.properties(propertyID);
require(msg.sender == propertyOwner);
uint256 whenToBecomePublic = 0;
uint256 rewardedAmount = 0;
if (setPrivateMode) {
//If inprivate, we can extend the duration, otherwise if becomePublic > now it means a free-use user locked it
require(propertyIsInPrivateMode || propertyBecomePublic <= now || propertyLastUpdater == msg.sender );
require(numMinutesPrivate > 0);
require(pxlProperty.balanceOf(msg.sender) >= numMinutesPrivate);
// Determines when the Property becomes public, one payout interval per coin burned
whenToBecomePublic = (now < propertyBecomePublic ? propertyBecomePublic : now) + PROPERTY_GENERATION_PAYOUT_INTERVAL * numMinutesPrivate;
rewardedAmount = getProjectedPayout(propertyIsInPrivateMode, propertyLastUpdate, propertyEarnUntil);
if (rewardedAmount > 0 && propertyLastUpdater != 0) {
pxlProperty.burnPXLRewardPXLx2(msg.sender, numMinutesPrivate, propertyLastUpdater, rewardedAmount, msg.sender, rewardedAmount);
} else {
pxlProperty.burnPXL(msg.sender, numMinutesPrivate);
}
} else {
// If its in private mode and still has time left, reimburse them for N-1 minutes tokens back
if (propertyIsInPrivateMode && propertyBecomePublic > now) {
pxlProperty.rewardPXL(msg.sender, ((propertyBecomePublic - now) / PROPERTY_GENERATION_PAYOUT_INTERVAL) - 1);
}
}
pxlProperty.setPropertyPrivateModeEarnUntilLastUpdateBecomePublic(propertyID, setPrivateMode, 0, 0, whenToBecomePublic);
if (setPrivateMode) {
SetPropertyPrivate(propertyID, numMinutesPrivate, propertyLastUpdater, rewardedAmount);
} else {
SetPropertyPublic(propertyID);
}
}
// Transfer Property ownership between accounts. This has no cost, no cut and does not change flag status
function transferProperty(uint16 propertyID, address newOwner) public validPropertyID(propertyID) returns(bool) {
require(pxlProperty.getPropertyOwner(propertyID) == msg.sender);
_transferProperty(propertyID, newOwner, 0, 0, pxlProperty.getPropertyFlag(propertyID), msg.sender);
return true;
}
// Purchase a unowned system-Property in a combination of PXL and ETH
function buyProperty(uint16 propertyID, uint256 pxlValue) public validPropertyID(propertyID) payable returns(bool) {
//Must be the first purchase, otherwise do it with PXL from another user
require(pxlProperty.getPropertyOwner(propertyID) == 0);
// Must be able to afford the given PXL
require(pxlProperty.balanceOf(msg.sender) >= pxlValue);
require(pxlValue != 0);
// Protect against underflow
require(pxlValue <= systemSalePricePXL);
uint256 pxlLeft = systemSalePricePXL - pxlValue;
uint256 ethLeft = systemSalePriceETH / systemSalePricePXL * pxlLeft;
// Must have spent enough ETH to cover the ETH left after PXL price was subtracted
require(msg.value >= ethLeft);
pxlProperty.burnPXLRewardPXL(msg.sender, pxlValue, owner, pxlValue);
systemPXLStepTally += uint16(100 * pxlValue / systemSalePricePXL);
if (systemPXLStepTally >= 1000) {
systemPXLStepCount++;
systemSalePricePXL += systemSalePricePXL * 9 / systemPXLStepCount / 10;
systemPXLStepTally -= 1000;
}
ownerEth += msg.value;
systemETHStepTally += uint16(100 * pxlLeft / systemSalePricePXL);
if (systemETHStepTally >= 1000) {
systemETHStepCount++;
systemSalePriceETH += systemSalePriceETH * 9 / systemETHStepCount / 10;
systemETHStepTally -= 1000;
}
_transferProperty(propertyID, msg.sender, msg.value, pxlValue, 0, 0);
return true;
}
// Purchase a listed user-owner Property in PXL
function buyPropertyInPXL(uint16 propertyID, uint256 PXLValue) public validPropertyID(propertyID) {
// If Property is system-owned
var (propertyOwner, propertySalePrice) = pxlProperty.getPropertyOwnerSalePrice(propertyID);
address originalOwner = propertyOwner;
if (propertyOwner == 0) {
// Turn it into a user-owned at system price with contract owner as owner
pxlProperty.setPropertyOwnerSalePrice(propertyID, owner, systemSalePricePXL);
propertyOwner = owner;
propertySalePrice = systemSalePricePXL;
// Increase system PXL price
systemPXLStepTally += 100;
if (systemPXLStepTally >= 1000) {
systemPXLStepCount++;
systemSalePricePXL += systemSalePricePXL * 9 / systemPXLStepCount / 10;
systemPXLStepTally -= 1000;
}
}
require(propertySalePrice <= PXLValue);
uint256 amountTransfered = propertySalePrice * USER_BUY_CUT_PERCENT / 100;
pxlProperty.burnPXLRewardPXLx2(msg.sender, propertySalePrice, propertyOwner, amountTransfered, owner, (propertySalePrice - amountTransfered));
_transferProperty(propertyID, msg.sender, 0, propertySalePrice, 0, originalOwner);
}
// Purchase a system-Property in pure ETH
function buyPropertyInETH(uint16 propertyID) public validPropertyID(propertyID) payable returns(bool) {
require(pxlProperty.getPropertyOwner(propertyID) == 0);
require(msg.value >= systemSalePriceETH);
ownerEth += msg.value;
systemETHStepTally += 100;
if (systemETHStepTally >= 1000) {
systemETHStepCount++;
systemSalePriceETH += systemSalePriceETH * 9 / systemETHStepCount / 10;
systemETHStepTally -= 1000;
}
_transferProperty(propertyID, msg.sender, msg.value, 0, 0, 0);
return true;
}
// Property owner lists their Property for sale at their preferred price
function listForSale(uint16 propertyID, uint256 price) public validPropertyID(propertyID) returns(bool) {
require(price != 0);
require(msg.sender == pxlProperty.getPropertyOwner(propertyID));
pxlProperty.setPropertySalePrice(propertyID, price);
PropertySetForSale(propertyID, price);
return true;
}
// Property owner delists their Property from being for sale
function delist(uint16 propertyID) public validPropertyID(propertyID) returns(bool) {
require(msg.sender == pxlProperty.getPropertyOwner(propertyID));
pxlProperty.setPropertySalePrice(propertyID, 0);
DelistProperty(propertyID);
return true;
}
// Make a public bid and notify a Property owner of your bid. Burn 1 coin
function makeBid(uint16 propertyID, uint256 bidAmount) public validPropertyID(propertyID) {
require(bidAmount > 0);
require(pxlProperty.balanceOf(msg.sender) >= 1 + bidAmount);
Bid(propertyID, bidAmount, now);
pxlProperty.burnPXL(msg.sender, 1);
}
/* CONTRACT OWNER FUNCTIONS */
// Contract owner can withdraw up to ownerEth amount
function withdraw(uint256 amount) public ownerOnly() {
if (amount <= ownerEth) {
owner.transfer(amount);
ownerEth -= amount;
}
}
// Contract owner can withdraw ownerEth amount
function withdrawAll() public ownerOnly() {
owner.transfer(ownerEth);
ownerEth = 0;
}
// Contract owner can change who is the contract owner
function changeOwners(address newOwner) public ownerOnly() {
owner = newOwner;
}
/* ## PRIVATE FUNCTIONS ## */
// Function which wraps payouts for setColors
function _tryTriggerPayout(uint16 propertyID, uint256 pxlToSpend) private returns(bool) {
var (propertyFlag, propertyIsInPrivateMode, propertyOwner, propertyLastUpdater, propertySalePrice, propertyLastUpdate, propertyBecomePublic, propertyEarnUntil) = pxlProperty.properties(propertyID);
//If the Property is in private mode and expired, make it public
if (propertyIsInPrivateMode && propertyBecomePublic <= now) {
pxlProperty.setPropertyPrivateMode(propertyID, false);
propertyIsInPrivateMode = false;
}
//If its in private mode, only the owner can interact with it
if (propertyIsInPrivateMode) {
require(msg.sender == propertyOwner);
require(propertyFlag != 2);
//If if its in free-use mode
} else if (propertyBecomePublic <= now || propertyLastUpdater == msg.sender) {
uint256 pxlSpent = pxlToSpend + 1; //All pxlSpent math uses N+1, so built in for convenience
if (isInGracePeriod() && pxlToSpend < 2) { //If first 3 days and we spent <2 coins, treat it as if we spent 2
pxlSpent = 3; //We're treating it like 2, but it's N+1 in the math using this
}
uint256 projectedAmount = getProjectedPayout(propertyIsInPrivateMode, propertyLastUpdate, propertyEarnUntil);
pxlProperty.burnPXLRewardPXLx2(msg.sender, pxlToSpend, propertyLastUpdater, projectedAmount, propertyOwner, projectedAmount);
//BecomePublic = (N+1)/2 minutes of user-private mode
//EarnUntil = (N+1)*5 coins earned max/minutes we can earn from
pxlProperty.setPropertyBecomePublicEarnUntil(propertyID, now + (pxlSpent * PROPERTY_GENERATION_PAYOUT_INTERVAL / 2), now + (pxlSpent * 5 * PROPERTY_GENERATION_PAYOUT_INTERVAL));
} else {
return false;
}
pxlProperty.setPropertyLastUpdaterLastUpdate(propertyID, msg.sender, now);
return true;
}
// Transfer ownership of a Property and reset their info
function _transferProperty(uint16 propertyID, address newOwner, uint256 ethAmount, uint256 PXLAmount, uint8 flag, address oldOwner) private {
require(newOwner != 0);
pxlProperty.setPropertyOwnerSalePricePrivateModeFlag(propertyID, newOwner, 0, false, flag);
PropertyBought(propertyID, newOwner, ethAmount, PXLAmount, now, oldOwner);
}
// Gets the (owners address, Ethereum sale price, PXL sale price, last update timestamp, whether its in private mode or not, when it becomes public timestamp, flag) for a Property
function getPropertyData(uint16 propertyID) public validPropertyID(propertyID) view returns(address, uint256, uint256, uint256, bool, uint256, uint32) {
return pxlProperty.getPropertyData(propertyID, systemSalePriceETH, systemSalePricePXL);
}
// Gets the system ETH and PXL prices
function getSystemSalePrices() public view returns(uint256, uint256) {
return (systemSalePriceETH, systemSalePricePXL);
}
// Gets the sale prices of any Property in ETH and PXL
function getForSalePrices(uint16 propertyID) public validPropertyID(propertyID) view returns(uint256, uint256) {
if (pxlProperty.getPropertyOwner(propertyID) == 0) {
return getSystemSalePrices();
} else {
return (0, pxlProperty.getPropertySalePrice(propertyID));
}
}
// Gets the projected sale price for a property should it be triggered at this very moment
function getProjectedPayout(uint16 propertyID) public view returns(uint256) {
var (propertyIsInPrivateMode, propertyLastUpdate, propertyEarnUntil) = pxlProperty.getPropertyPrivateModeLastUpdateEarnUntil(propertyID);
return getProjectedPayout(propertyIsInPrivateMode, propertyLastUpdate, propertyEarnUntil);
}
function getProjectedPayout(bool propertyIsInPrivateMode, uint256 propertyLastUpdate, uint256 propertyEarnUntil) public view returns(uint256) {
if (!propertyIsInPrivateMode && propertyLastUpdate != 0) {
uint256 earnedUntil = (now < propertyEarnUntil) ? now : propertyEarnUntil;
uint256 minutesSinceLastColourChange = (earnedUntil - propertyLastUpdate) / PROPERTY_GENERATION_PAYOUT_INTERVAL;
return minutesSinceLastColourChange * PROPERTY_GENERATES_PER_MINUTE;
//return (((now < propertyEarnUntil) ? now : propertyEarnUntil - propertyLastUpdate) / PROPERTY_GENERATION_PAYOUT_INTERVAL) * PROPERTY_GENERATES_PER_MINUTE; //Gave too high number wtf?
}
return 0;
}
// Gets whether the contract is still in the intial grace period where we give extra features to color setters
function isInGracePeriod() public view returns(bool) {
return now <= GRACE_PERIOD_END_TIMESTAMP;
}
}
| return (((now < propertyEarnUntil) ? now : propertyEarnUntil - propertyLastUpdate) / PROPERTY_GENERATION_PAYOUT_INTERVAL) * PROPERTY_GENERATES_PER_MINUTE; Gave too high number wtf? | if (!propertyIsInPrivateMode && propertyLastUpdate != 0) {
uint256 earnedUntil = (now < propertyEarnUntil) ? now : propertyEarnUntil;
uint256 minutesSinceLastColourChange = (earnedUntil - propertyLastUpdate) / PROPERTY_GENERATION_PAYOUT_INTERVAL;
return minutesSinceLastColourChange * PROPERTY_GENERATES_PER_MINUTE;
}
return 0;
| 6,370,244 | [
1,
2463,
261,
12443,
3338,
411,
1272,
41,
1303,
9716,
13,
692,
2037,
294,
1272,
41,
1303,
9716,
300,
1272,
3024,
1891,
13,
342,
9759,
67,
13990,
2689,
67,
11389,
5069,
67,
16435,
13,
225,
9759,
67,
13990,
1777,
55,
67,
3194,
67,
30090,
31,
611,
836,
4885,
3551,
1300,
341,
6632,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
16051,
4468,
2520,
382,
6014,
2309,
597,
1272,
3024,
1891,
480,
374,
13,
288,
203,
5411,
2254,
5034,
425,
1303,
329,
9716,
273,
261,
3338,
411,
1272,
41,
1303,
9716,
13,
692,
2037,
294,
1272,
41,
1303,
9716,
31,
203,
5411,
2254,
5034,
6824,
9673,
3024,
26404,
3043,
273,
261,
73,
1303,
329,
9716,
300,
1272,
3024,
1891,
13,
342,
9759,
67,
13990,
2689,
67,
11389,
5069,
67,
16435,
31,
203,
5411,
327,
6824,
9673,
3024,
26404,
3043,
380,
9759,
67,
13990,
1777,
55,
67,
3194,
67,
30090,
31,
203,
3639,
289,
203,
3639,
327,
374,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xEA24e9Bac006DE9635Ac7fA4D767fFb64FB5645c/sources/contracts/vault/VaultCore.sol | * @notice Gets the vault configuration of a supported asset./ | function getAssetConfig(address _asset)
public
view
returns (Asset memory config)
{
config = assets[_asset];
}
| 4,918,528 | [
1,
3002,
326,
9229,
1664,
434,
279,
3260,
3310,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
24689,
809,
12,
2867,
389,
9406,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6672,
3778,
642,
13,
203,
565,
288,
203,
3639,
642,
273,
7176,
63,
67,
9406,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.8;
contract Ownable {
address public owner;
event OWNERSHIPTRANSFERRED742(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor() public {
owner = msg.sender;
}
modifier ONLYOWNER252() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP351(address newOwner) public ONLYOWNER252 { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED742(owner, newOwner);
owner = newOwner;
}
}
contract IERC721 {
event TRANSFER592(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL116(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL761(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF286(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF883(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function APPROVE279(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED445(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL429(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL922(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM675(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM377(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM377(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract ERC20BasicInterface {
function TOTALSUPPLY614() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF286(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER601(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM675(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER592(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
uint8 public decimals;
}
contract Bussiness is Ownable {
address public ceoAddress = address(0x6C3E879BDD20e9686cfD9BBD1bfD4B2Dd6d47079);
IERC721 public erc721Address = IERC721(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B);
ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba);
uint256 public ETHFee = 25; // 2,5 %
uint256 public Percen = 1000;
uint256 public HBWALLETExchange = 21;
// cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2
uint256 public limitETHFee = 2000000000000000;
uint256 public limitHBWALLETFee = 2;
uint256 public hightLightFee = 30000000000000000;
constructor() public {}
struct Price {
address payable tokenOwner;
uint256 price;
uint256 fee;
uint256 hbfee;
bool isHightlight;
}
uint[] public arrayTokenIdSale;
mapping(uint256 => Price) public prices;
modifier ONLYCEOADDRESS253() { //inject NONSTANDARD NAMING
require(msg.sender == ceoAddress);
_;
}
// Move the last element to the deleted spot.
// Delete the last element, then correct the length.
function _BURNARRAYTOKENIDSALE680(uint index) internal { //inject NONSTANDARD NAMING
require(index < arrayTokenIdSale.length);
arrayTokenIdSale[index] = arrayTokenIdSale[arrayTokenIdSale.length - 1];
delete arrayTokenIdSale[arrayTokenIdSale.length - 1];
arrayTokenIdSale.length--;
}
function OWNEROF883(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING
return erc721Address.OWNEROF883(_tokenId);
}
function BALANCEOF286() public view returns (uint256){ //inject NONSTANDARD NAMING
return address(this).balance;
}
function GETAPPROVED445(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING
return erc721Address.GETAPPROVED445(_tokenId);
}
function SETPRICE924(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING
prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight);
arrayTokenIdSale.push(_tokenId);
}
function SETPRICEFEEETH967(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable { //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee;
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
if(prices[_tokenId].price == 0) {
if (ethfee >= limitETHFee) {
require(msg.value == ethfee + hightLightFee);
} else {
require(msg.value == limitETHFee + hightLightFee);
ethfee = limitETHFee;
}
}
ethfee += prices[_tokenId].fee;
} else ethfee = _ethPrice * ETHFee / Percen;
SETPRICE924(_tokenId, _ethPrice, ethfee, 0, _isHightLight);
}
function SETPRICEFEEHBWALLET897(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){ //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 fee;
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
// ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18)
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee));
} else {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
} else {
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
}
SETPRICE924(_tokenId, _ethPrice, 0, fee, _isHightLight);
return true;
}
function REMOVEPRICE927(uint256 tokenId) public returns (uint256){ //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(tokenId) == msg.sender);
if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee);
else if (prices[tokenId].hbfee > 0) hbwalletToken.TRANSFER601(msg.sender, prices[tokenId].hbfee);
RESETPRICE775(tokenId);
return prices[tokenId].price;
}
function SETFEE284(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public ONLYOWNER252 returns (uint256, uint256, uint256){ //inject NONSTANDARD NAMING
require(_ethFee > 0 && _HBWALLETExchange > 0 && _hightLightFee > 0);
ETHFee = _ethFee;
HBWALLETExchange = _HBWALLETExchange;
hightLightFee = _hightLightFee;
return (ETHFee, HBWALLETExchange, hightLightFee);
}
function SETLIMITFEE654(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public ONLYOWNER252 returns (uint256, uint256){ //inject NONSTANDARD NAMING
require(_ethlimitFee > 0 && _hbWalletlimitFee > 0);
limitETHFee = _ethlimitFee;
limitHBWALLETFee = _hbWalletlimitFee;
return (limitETHFee, limitHBWALLETFee);
}
function WITHDRAW821(address payable _address, uint256 amount, uint256 _amountHB) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.BALANCEOF286(address(this)) >= _amountHB);
_address.transfer(amount);
hbwalletToken.TRANSFERFROM675(address(this), _address, _amountHB);
}
function CANCELBUSSINESS265() public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.OWNEROF883(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0 && address(this).balance >= prices[arrayTokenIdSale[i]].fee) {
prices[arrayTokenIdSale[i]].tokenOwner.transfer(prices[arrayTokenIdSale[i]].fee);
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0 && hbwalletToken.BALANCEOF286(address(this)) >= prices[arrayTokenIdSale[i]].hbfee) {
hbwalletToken.TRANSFER601(prices[arrayTokenIdSale[i]].tokenOwner, prices[arrayTokenIdSale[i]].hbfee);
}
}
RESETPRICE775(arrayTokenIdSale[i]);
}
}
function CHANGECEO557(address _address) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
require(_address != address(0));
ceoAddress = _address;
}
function BUY787(uint256 tokenId) public payable { //inject NONSTANDARD NAMING
require(GETAPPROVED445(tokenId) == address(this));
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
RESETPRICE775(tokenId);
}
function BUYWITHOUTCHECKAPPROVED538(uint256 tokenId) public payable { //inject NONSTANDARD NAMING
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
RESETPRICE775(tokenId);
}
function RESETPRICE775(uint256 tokenId) private { //inject NONSTANDARD NAMING
prices[tokenId] = Price(address(0), 0, 0, 0, false);
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (arrayTokenIdSale[i] == tokenId) {
_BURNARRAYTOKENIDSALE680(i);
}
}
}
} | inject NONSTANDARD NAMING
| modifier ONLYOWNER252() { | 7,237,353 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
20747,
29602,
2947,
22,
1435,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xCfc50C98e98e44C00A3867cC21fCC1809b9e8aa2/sources/LANToken.sol | One address is one claim
| require(!claimed[msg.sender], "Already claimed"); | 11,086,697 | [
1,
3335,
1758,
353,
1245,
7516,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
6528,
12,
5,
14784,
329,
63,
3576,
18,
15330,
6487,
315,
9430,
7516,
329,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/optimism/l1/NativeOptimism.sol | interfaceId to be set offchain which is used to select one of the 3 kinds of bridging (standard bridge / old standard / synthetic) currencyKey of the token beingBridged socket offchain created hash address of receiver of bridged tokens Gas limit required to complete the deposit on L2. Address of the L1 respective L2 ERC20 additional data , for ll contracts this will be 0x data or empty data | struct OptimismBridgeData {
uint256 interfaceId;
bytes32 currencyKey;
bytes32 metadata;
address receiverAddress;
address customBridgeAddress;
address token;
uint32 l2Gas;
address l2Token;
bytes data;
}
| 11,003,300 | [
1,
5831,
548,
358,
506,
444,
3397,
5639,
1492,
353,
1399,
358,
2027,
1245,
434,
326,
890,
21961,
434,
324,
1691,
1998,
261,
10005,
10105,
342,
1592,
4529,
342,
25535,
13,
5462,
653,
434,
326,
1147,
3832,
38,
1691,
2423,
2987,
3397,
5639,
2522,
1651,
1758,
434,
5971,
434,
324,
1691,
2423,
2430,
31849,
1800,
1931,
358,
3912,
326,
443,
1724,
603,
511,
22,
18,
5267,
434,
326,
511,
21,
17613,
511,
22,
4232,
39,
3462,
3312,
501,
269,
364,
6579,
20092,
333,
903,
506,
374,
92,
501,
578,
1008,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
19615,
6228,
13691,
751,
288,
203,
3639,
2254,
5034,
1560,
548,
31,
203,
3639,
1731,
1578,
5462,
653,
31,
203,
3639,
1731,
1578,
1982,
31,
203,
3639,
1758,
5971,
1887,
31,
203,
3639,
1758,
1679,
13691,
1887,
31,
203,
3639,
1758,
1147,
31,
203,
3639,
2254,
1578,
328,
22,
27998,
31,
203,
3639,
1758,
328,
22,
1345,
31,
203,
3639,
1731,
501,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../AppInterface.sol";
import "./IRandom.sol";
import "../lib/ECDSA.sol";
import "../lib/SafeMath.sol";
/**
* @notice Support mainstream gaming: flip-coin, dice, two-dice, etheroll
*/
contract DiceGame is AppInterface {
using ECDSA for bytes32;
using SafeMath for uint;
// max bits of betMask when playing flip-coin, dice, two-dice
uint256 constant MAX_MASK_MODULO = 36;
/* States */
IRandom public randomContract;
struct Result {
// 0=nobody commit game proof, refund lock value
// 1=commit game proof succeed, distribute value with game result
uint status;
address initiator;
address acceptor;
uint iStake;
uint aStake;
uint betMask;
uint modulo;
}
// gameID => game result
mapping(bytes32 => Result) public resultMap;
/* Constructor */
constructor(address _randomContract) public {
randomContract = IRandom(_randomContract);
}
/* Events */
event CommitProof(bytes32 indexed gameID, address indexed initiator, address indexed acceptor);
/* External Functions */
/**
* @notice Called by payment channel to distribute lock value
* @param gameID id of game, the same to lockID
* @param gamer1 address of a gamer
* @param gamer2 address of the other gamer
* @return (status, balance of gamer1, balance of gamer2)
*/
function getResult(bytes32 gameID, address gamer1, address gamer2) external returns(uint, uint, uint) {
Result storage result = resultMap[gameID];
if(result.status == 0) {
return (0, 0, 0);
}
// 0=nobody commit random proof, refund lock value
// 1=initiator did not reveal pre-image, winner is acceptor
// 2=get random succeed
uint status;
// if status == 2, use random
bytes32 random;
// if status == 1, use winner
address winner;
(status, random, winner) = randomContract.getRandom(gameID, result.initiator, result.acceptor);
if(status == 0) {
return (0, 0, 0);
} else if(status == 2) {
winner = isInitiatorWin(result.betMask, result.modulo, random) ? result.initiator : result.acceptor;
}
return gamer1 == winner ? (1, result.iStake.safeAdd(result.aStake), uint(0)) : (1, uint(0), result.iStake.safeAdd(result.aStake));
}
/* Public Functions */
/**
* @notice Commit game proof when disputing off-chain
* @param round game round
* @param channelID id of channel two gamers in
* @param initiator address of one peer who trigger game
* @param acceptor address of the other peer who accept game
* @param iStake bet stake of initiator, which locked in channel
* @param aStake bet stake of acceptor, which locked in channel
* @param betMask outcome initiator bet on, and acceptor bet on the other side automatic
* @param modulo which kind of game: 1=flip-coin, 6=dice, 36=two-dice, 100=etheroll
* @param iSig signature of initiator
* @param aSig signature of acceptor
*/
function commitProof(uint round, bytes32 channelID, address initiator, address acceptor, uint256 iStake, uint256 aStake, uint256 betMask, uint256 modulo, bytes memory iSig, bytes memory aSig) public {
bytes32 hash = keccak256(abi.encodePacked(round, channelID, initiator, acceptor, iStake, aStake, betMask, modulo));
require(hash.recover(iSig) == initiator, "invalid signature of initiator");
require(hash.recover(aSig) == acceptor, "invalid signature of acceptor");
bytes32 gameID = keccak256(abi.encodePacked(channelID, getPeersHash(initiator, acceptor), round));
Result storage result = resultMap[gameID];
result.status = 1;
result.initiator = initiator;
result.acceptor = acceptor;
result.iStake = iStake;
result.aStake = aStake;
result.betMask = betMask;
result.modulo = modulo;
emit CommitProof(gameID, initiator, acceptor);
}
/* Internal Functions */
function isInitiatorWin(uint256 betMask, uint256 modulo, bytes32 random) internal returns(bool) {
uint256 dice = uint256(random) % modulo;
if (modulo <= MAX_MASK_MODULO) {
return ((2 ** dice) & uint40(betMask)) != 0 ? true : false;
} else {
return dice < betMask ? true : false;
}
}
function getPeersHash(address peer1, address peer2) public pure returns (bytes32) {
require(peer1 != address(0x0) && peer2 != address(0x0) && peer1 != peer2, "invalid peer address");
if (peer1 < peer2) {
return keccak256(abi.encodePacked(peer1, peer2));
} else {
return keccak256(abi.encodePacked(peer2, peer1));
}
}
} | 0=nobody commit random proof, refund lock value 1=initiator did not reveal pre-image, winner is acceptor 2=get random succeed | uint status;
| 14,020,629 | [
1,
20,
33,
82,
947,
973,
3294,
2744,
14601,
16,
16255,
2176,
460,
404,
33,
2738,
10620,
5061,
486,
283,
24293,
675,
17,
2730,
16,
5657,
1224,
353,
2791,
280,
576,
33,
588,
2744,
12897,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1267,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xE078D1805884f0c2f83C833c38DD1837cb248c7F/sources/contracts/CMMessage.sol | convert to denomination with chainlink add to pouchValueTotal | function addPouch(address _pouchAddress) override external returns (uint256 _pouchCount, uint256 _totalPouchValue, string memory _messageDenomination){
isLocked();
IcmPouch pouch = IcmPouch(_pouchAddress);
require(pouch.getOwner() == msg.sender, "pouch owner only");
pouchByName[pouch.getName()] = _pouchAddress;
pouchList.push(_pouchAddress);
(uint256 fundsTotal_, string memory pouchDenomination_) = pouch.getFundsData();
if(!isEqual(pouchDenomination_, denomination_symbol)){
uint256 denominatedValue_ = chainlink.getDenominatedValue(pouchDenomination_, denomination_symbol, fundsTotal_);
pouchValueTotal += denominatedValue_;
}
else {
pouchValueTotal += fundsTotal_;
}
return (pouchList.length, pouchValueTotal, denomination_symbol);
}
| 13,206,127 | [
1,
6283,
358,
10716,
1735,
598,
2687,
1232,
527,
358,
293,
7309,
620,
5269,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
52,
7309,
12,
2867,
389,
84,
7309,
1887,
13,
225,
3849,
3903,
1135,
261,
11890,
5034,
389,
84,
7309,
1380,
16,
2254,
5034,
389,
4963,
52,
7309,
620,
16,
533,
3778,
389,
2150,
8517,
362,
1735,
15329,
203,
3639,
31753,
5621,
203,
3639,
467,
7670,
52,
7309,
293,
7309,
273,
467,
7670,
52,
7309,
24899,
84,
7309,
1887,
1769,
203,
203,
3639,
2583,
12,
84,
7309,
18,
588,
5541,
1435,
422,
1234,
18,
15330,
16,
315,
84,
7309,
3410,
1338,
8863,
203,
203,
203,
3639,
293,
7309,
5911,
63,
84,
7309,
18,
17994,
1435,
65,
273,
389,
84,
7309,
1887,
31,
7010,
3639,
293,
7309,
682,
18,
6206,
24899,
84,
7309,
1887,
1769,
203,
203,
3639,
261,
11890,
5034,
284,
19156,
5269,
67,
16,
533,
3778,
293,
7309,
8517,
362,
1735,
67,
13,
273,
293,
7309,
18,
588,
42,
19156,
751,
5621,
203,
3639,
203,
4202,
309,
12,
5,
291,
5812,
12,
84,
7309,
8517,
362,
1735,
67,
16,
10716,
1735,
67,
7175,
3719,
95,
203,
4202,
2254,
5034,
10716,
7458,
620,
67,
273,
2687,
1232,
18,
588,
8517,
362,
7458,
620,
12,
84,
7309,
8517,
362,
1735,
67,
16,
10716,
1735,
67,
7175,
16,
284,
19156,
5269,
67,
1769,
203,
203,
5411,
293,
7309,
620,
5269,
1011,
10716,
7458,
620,
67,
31,
203,
4202,
289,
203,
4202,
469,
288,
7010,
6647,
293,
7309,
620,
5269,
1011,
284,
19156,
5269,
67,
31,
7010,
4202,
289,
203,
203,
203,
4202,
327,
261,
84,
7309,
682,
18,
2469,
16,
293,
7309,
620,
5269,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-03
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* 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);
/**
* 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);
/**
* 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);
/**
* 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);
function decimals() external view returns (uint8);
/**
* 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);
/**
* 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/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* 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 {
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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");
}
/**
* Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* Collection of functions related to the address type
*/
library Address {
/**
* Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* 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");
}
/**
* 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");
}
/**
* 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);
}
/**
* 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");
}
/**
* Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* 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;
}
/**
* Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* 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 override returns (uint8) {
return _decimals;
}
/**
* See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* 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;
}
/**
* See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** 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");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* 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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* 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);
}
/**
* 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_;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* 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);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/zs-FEI.sol
// zsTokens are Stabilize proxy tokens that serve as receipts for deposits into Stabilize strategies
// zsTokens should increase in value if the strategy it uses is profitable
// When someone deposits into the zsToken contract, tokens are minted and when they redeem, tokens are burned
// Users by default withdraw from main pool before collateral pool
interface StabilizeStrategy {
function rewardTokensCount() external view returns (uint256);
function rewardTokenAddress(uint256) external view returns (address);
function withdrawTokenReserves() external view returns (address, uint256);
function balance() external view returns (uint256);
function pricePerToken() external view returns (uint256);
function enter() external;
function exit() external;
function deposit(bool) external;
function withdraw(address, uint256, uint256, bool) external returns (uint256); // Will withdraw to the address specified a percent of total shares
}
pragma solidity ^0.6.6;
contract zsToken is ERC20("Stabilize Strategy FEI", "zs-FEI"), Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Variables
uint256 constant DIVISION_FACTOR = 100000;
// There are no fees to deposit and withdraw from the zs-Tokens
// Info of each user.
struct UserInfo {
uint256 depositTime; // The time the user made the last deposit
uint256 shareEstimate;
}
mapping(address => UserInfo) private userInfo;
// Token information
// This is a single asset wrapper that only accepts main token
// FEI, USDC
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
address private _underlyingPriceAsset; // Token from which the price is derived for STBZ staking
bool public depositsOpen = true; // Governance can open or close deposits without timelock, cannot block withdrawals
// Strategy information
StabilizeStrategy private currentStrategy; // This will be the contract for the strategy
address private _pendingStrategy;
// Events
event Wrapped(address indexed user, uint256 amount);
event Unwrapped(address indexed user, uint256 amount);
constructor (address _priceAsset) public {
_underlyingPriceAsset = _priceAsset;
setupWithdrawTokens();
}
function setupWithdrawTokens() internal {
// Start with FEI
IERC20 _token = IERC20(address(0x956F47F50A910163D8BF957Cf5846D573E7f87CA));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// USDC
_token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
function getCurrentStrategy() external view returns (address) {
return address(currentStrategy);
}
function getPendingStrategy() external view returns (address) {
return _pendingStrategy;
}
function underlyingAsset() public view returns (address) {
// Can be used if staking in the STBZ pool
return address(_underlyingPriceAsset);
}
function underlyingDepositAssets() public view returns (address, address) {
// Returns all addresses accepted by this token vault
return (address(tokenList[0].token), address(tokenList[1].token));
}
function pricePerToken() public view returns (uint256) {
if(totalSupply() == 0){
return 1e18; // Shown in Wei units
}else{
return uint256(1e18).mul(valueOfVaultAndStrategy()).div(totalSupply());
}
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
uint256 _balance = 0;
for(uint256 i = 0; i < tokenList.length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function valueOfVaultAndStrategy() public view returns (uint256) { // The total value of the tokens
uint256 balance = getNormalizedTotalBalance(address(this)); // Get tokens stored in this contract
if(currentStrategy != StabilizeStrategy(address(0))){
balance += currentStrategy.balance(); // And tokens stored at the strategy
}
return balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token of main token, and if none available, the collateral asset
if(currentStrategy != StabilizeStrategy(address(0))){
return currentStrategy.withdrawTokenReserves();
}else{
if(tokenList[0].token.balanceOf(address(this)) > 0){
return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this)));
}else if(tokenList[1].token.balanceOf(address(this)) > 0){
return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
}
// Now handle deposits into the strategy
function deposit(uint256 amount) public nonReentrant {
uint256 total = valueOfVaultAndStrategy(); // Get token equivalent at strategy and here if applicable
require(depositsOpen == true, "Deposits have been suspended, but you can still withdraw");
require(currentStrategy != StabilizeStrategy(address(0)),"No strategy contract has been selected yet");
IERC20 _token = tokenList[0].token; // Trusted tokens
uint256 _before = _token.balanceOf(address(this));
_token.safeTransferFrom(_msgSender(), address(this), amount); // Transfer token to this address
amount = _token.balanceOf(address(this)).sub(_before); // Some tokens lose amount (transfer fee) upon transfer
require(amount > 0, "Cannot deposit 0");
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract
}
uint256 _strategyBalance = currentStrategy.balance(); // Will get the balance of the value of the main tokens at the strategy
// Now call the strategy to deposit
pushTokensToStrategy(); // Push any strategy tokens here into the strategy
currentStrategy.deposit(nonContract); // Activate strategy deposit
require(currentStrategy.balance() > _strategyBalance, "No change in strategy balance"); // Balance should increase
uint256 normalizedAmount = amount.mul(1e18).div(10**tokenList[0].decimals); // Make sure everything is same units
uint256 mintAmount = normalizedAmount;
if(totalSupply() > 0){
// There is already a balance here, calculate our share
mintAmount = normalizedAmount.mul(totalSupply()).div(total); // Our share of the total
}
_mint(_msgSender(),mintAmount); // Now mint new zs-token to the depositor
// Add the user information
userInfo[_msgSender()].depositTime = now;
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.add(mintAmount);
emit Wrapped(_msgSender(), amount);
}
function redeem(uint256 share) public nonReentrant {
// Essentially withdraw our equivalent share of the pool based on share value
// Users cannot choose which token they get. They get main token then collateral if available
require(share > 0, "Cannot withdraw 0");
require(totalSupply() > 0, "No value redeemable");
uint256 tokenTotal = totalSupply();
// Now burn the token
_burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract, we will allow market sells and buys
}else{
// This is a contract redeeming
require(userInfo[_msgSender()].depositTime < now && userInfo[_msgSender()].depositTime > 0, "Contract depositor cannot redeem in same transaction");
}
// Update user information
if(share <= userInfo[_msgSender()].shareEstimate){
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.sub(share);
}else{
// Share is greater than our share estimate, can happen if tokens are transferred
userInfo[_msgSender()].shareEstimate = 0;
require(nonContract == true, "Contract depositors cannot take out more than what they put in");
}
uint256 withdrawAmount = 0;
if(currentStrategy != StabilizeStrategy(address(0))){
withdrawAmount = currentStrategy.withdraw(_msgSender(), share, tokenTotal, nonContract); // Returns the amount of underlying removed
require(withdrawAmount > 0, "Failed to withdraw from the strategy");
}else{
// Pull directly from this contract the token amount in relation to the share if strategy not used
if(share < tokenTotal){
uint256 _balance = getNormalizedTotalBalance(address(this));
uint256 _myBalance = _balance.mul(share).div(tokenTotal);
withdrawPerOrder(_msgSender(), _myBalance, false); // This will withdraw based on token balanace
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
uint256 _balance = getNormalizedTotalBalance(address(this));
withdrawPerOrder(_msgSender(), _balance, true);
withdrawAmount = _balance;
}
}
emit Unwrapped(_msgSender(), withdrawAmount);
}
// This will withdraw the tokens from the contract based on order, essentially main token then collateral
function withdrawPerOrder(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
for(uint256 i = 0; i < length; i++){
// Determine the balance left
uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[i].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
// Governance functions
// Stop/start all deposits, no timelock required
// --------------------
function stopDeposits() external onlyGovernance {
depositsOpen = false;
}
function startDeposits() external onlyGovernance {
depositsOpen = true;
}
// A function used in case of strategy failure, possibly due to bug in the platform our strategy is using, governance can stop using it quick
function emergencyStopStrategy() external onlyGovernance {
depositsOpen = false;
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(address(0));
_timelockType = 0; // Prevent governance from changing to new strategy without timelock
}
// --------------------
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(totalSupply() > 0){
// Timelock is only required after tokens exist
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeStrategy(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
_pendingStrategy = _address;
if(totalSupply() == 0){
// Can change strategy with one call in this case
finishChangeStrategy();
}
}
function finishChangeStrategy() public onlyGovernance timelockConditionsMet(2) {
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(_timelock_address);
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
pushTokensToStrategy(); // It will push any strategy reward tokens here to the new strategy
currentStrategy.enter(); // Puts all the tokens and accessory tokens into the new strategy
}
_pendingStrategy = address(0);
}
function pushTokensToStrategy() internal {
uint256 tokenCount = currentStrategy.rewardTokensCount();
for(uint256 i = 0; i < tokenCount; i++){
IERC20 _token = IERC20(address(currentStrategy.rewardTokenAddress(i)));
uint256 _balance = _token.balanceOf(address(this));
if(_balance > 0){
_token.safeTransfer(address(currentStrategy), _balance);
}
}
}
// --------------------
} | Pull directly from this contract the token amount in relation to the share if strategy not used We are all shares, transfer all | if(currentStrategy != StabilizeStrategy(address(0))){
require(withdrawAmount > 0, "Failed to withdraw from the strategy");
if(share < tokenTotal){
uint256 _balance = getNormalizedTotalBalance(address(this));
uint256 _myBalance = _balance.mul(share).div(tokenTotal);
withdrawAmount = _myBalance;
uint256 _balance = getNormalizedTotalBalance(address(this));
withdrawPerOrder(_msgSender(), _balance, true);
withdrawAmount = _balance;
}
}
emit Unwrapped(_msgSender(), withdrawAmount);
| 2,002,184 | [
1,
9629,
5122,
628,
333,
6835,
326,
1147,
3844,
316,
2533,
358,
326,
7433,
309,
6252,
486,
1399,
1660,
854,
777,
24123,
16,
7412,
777,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
12,
2972,
4525,
480,
934,
22681,
554,
4525,
12,
2867,
12,
20,
3719,
15329,
203,
5411,
2583,
12,
1918,
9446,
6275,
405,
374,
16,
315,
2925,
358,
598,
9446,
628,
326,
6252,
8863,
203,
5411,
309,
12,
14419,
411,
1147,
5269,
15329,
203,
7734,
2254,
5034,
389,
12296,
273,
336,
15577,
5269,
13937,
12,
2867,
12,
2211,
10019,
203,
7734,
2254,
5034,
389,
4811,
13937,
273,
389,
12296,
18,
16411,
12,
14419,
2934,
2892,
12,
2316,
5269,
1769,
203,
7734,
598,
9446,
6275,
273,
389,
4811,
13937,
31,
203,
7734,
2254,
5034,
389,
12296,
273,
336,
15577,
5269,
13937,
12,
2867,
12,
2211,
10019,
203,
7734,
598,
9446,
2173,
2448,
24899,
3576,
12021,
9334,
389,
12296,
16,
638,
1769,
203,
7734,
598,
9446,
6275,
273,
389,
12296,
31,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
3639,
3626,
1351,
18704,
24899,
3576,
12021,
9334,
598,
9446,
6275,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
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: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
pragma solidity ^0.6.0;
/**
* @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.
*/
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 () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// 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/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ISparkleTimestamp.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
/**
* @dev Sparkle Timestamp Contract
* @author SparkleMobile Inc. (c) 2019-2020
*/
interface ISparkleTimestamp {
/**
* @dev Add new reward timestamp for address
* @param _rewardAddress being added to timestamp collection
*/
function addTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Reset timestamp maturity for loyalty address
* @param _rewardAddress to have reward period reset
*/
function resetTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Zero/delete existing loyalty timestamp entry
* @param _rewardAddress being requested for timestamp deletion
* @notice Test(s) not passed
*/
function deleteTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Get address confirmation for loyalty address
* @param _rewardAddress being queried for address information
*/
function getAddress(address _rewardAddress)
external
returns(address);
/**
* @dev Get timestamp of initial joined timestamp for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getJoinedTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of last deposit for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getDepositTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of reward maturity for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getRewardTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Determine if address specified has a timestamp record
* @param _rewardAddress being queried for timestamp existance
*/
function hasTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Calculate time remaining in seconds until this address' reward matures
* @param _rewardAddress to query remaining time before reward matures
*/
function getTimeRemaining(address _rewardAddress)
external
returns(uint256, bool, uint256);
/**
* @dev Determine if reward is mature for address
* @param _rewardAddress Address requesting addition in to loyalty timestamp collection
*/
function isRewardReady(address _rewardAddress)
external
returns(bool);
/**
* @dev Change the stored loyalty controller contract address
* @param _newAddress of new loyalty controller contract address
*/
function setContractAddress(address _newAddress)
external;
/**
* @dev Return the stored authorized controller address
* @return Address of loyalty controller contract
*/
function getContractAddress()
external
returns(address);
/**
* @dev Change the stored loyalty time period
* @param _newTimePeriod of new reward period (in seconds)
*/
function setTimePeriod(uint256 _newTimePeriod)
external;
/**
* @dev Return the current loyalty timer period
* @return Current stored value of loyalty time period
*/
function getTimePeriod()
external
returns(uint256);
/**
* @dev Event signal: Reset timestamp
*/
event ResetTimestamp(address _rewardAddress);
/**
* @dev Event signal: Loyalty contract address waws changed
*/
event ContractAddressChanged(address indexed _previousAddress, address indexed _newAddress);
/**
* @dev Event signal: Loyalty reward time period was changed
*/
event TimePeriodChanged( uint256 indexed _previousTimePeriod, uint256 indexed _newTimePeriod);
/**
* @dev Event signal: Loyalty reward timestamp was added
*/
event TimestampAdded( address indexed _newTimestampAddress );
/**
* @dev Event signal: Loyalty reward timestamp was removed
*/
event TimestampDeleted( address indexed _newTimestampAddress );
/**
* @dev Event signal: Timestamp for address was reset
*/
event TimestampReset(address _rewardAddress);
}
// File: contracts/ISparkleRewardTiers.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol';
// import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol';
/**
* @title A contract for managing reward tiers
* @author SparkleLoyalty Inc. (c) 2019-2020
*/
// interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard {
interface ISparkleRewardTiers {
/**
* @dev Add a new reward tier to the contract for future proofing
* @param _index of the new reward tier to add
* @param _rate of the added reward tier
* @param _price of the added reward tier
* @param _enabled status of the added reward tier
* @notice Test(s) Need rewrite
*/
function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Update an existing reward tier with new values
* @param _index of reward tier to update
* @param _rate of the reward tier
* @param _price of the reward tier
* @param _enabled status of the reward tier
* @return (bool) indicating success/failure
* @notice Test(s) Need rewrite
*/
function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Remove an existing reward tier from list of tiers
* @param _index of reward tier to remove
* @notice Test(s) Need rewrite
*/
function deleteTier(uint256 _index)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Get the rate value of specified tier
* @param _index of tier to query
* @return specified reward tier rate
* @notice Test(s) Need rewrite
*/
function getRate(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get price of tier
* @param _index of tier to query
* @return uint256 indicating tier price
* @notice Test(s) Need rewrite
*/
function getPrice(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get the enabled status of tier
* @param _index of tier to query
* @return bool indicating status of tier
* @notice Test(s) Need rewrite
*/
function getEnabled(uint256 _index)
external
// view
// whenNotPaused
returns(bool);
/**
* @dev Withdraw ether that has been sent directly to the contract
* @return bool indicating withdraw success
* @notice Test(s) Need rewrite
*/
function withdrawEth()
external
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Event triggered when a reward tier is deleted
* @param _index of tier to deleted
*/
event TierDeleted(uint256 _index);
/**
* @dev Event triggered when a reward tier is updated
* @param _index of the updated tier
* @param _rate of updated tier
* @param _price of updated tier
* @param _enabled status of updated tier
*/
event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
/**
* @dev Event triggered when a new reward tier is added
* @param _index of the tier added
* @param _rate of added tier
* @param _price of added tier
* @param _enabled status of added tier
*/
event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
}
// File: contracts/SparkleLoyalty.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
/**
* @dev Sparkle Loyalty Rewards
* @author SparkleMobile Inc.
*/
contract SparkleLoyalty is Ownable, Pausable, ReentrancyGuard {
/**
* @dev Ensure math safety through SafeMath
*/
using SafeMath for uint256;
// Gas to send with certain transations that may cost more in the future due to chain growth
uint256 private gasToSendWithTX = 25317;
// Base rate APR (5%) factored to 365.2422 gregorian days
uint256 private baseRate = 0.00041069 * 10e7; // A full year is 365.2422 gregorian days (5%)
// Account data structure
struct Account {
address _address; // Loyalty reward address
uint256 _balance; // Total tokens deposited
uint256 _collected; // Total tokens collected
uint256 _claimed; // Total succesfull reward claims
uint256 _joined; // Total times address has joined
uint256 _tier; // Tier index of reward tier
bool _isLocked; // Is the account locked
}
// tokenAddress of erc20 token address
address private tokenAddress;
// timestampAddress of time stamp contract address
address private timestampAddress;
// treasuryAddress of token treeasury address
address private treasuryAddress;
// collectionAddress to receive eth payed for tier upgrades
address private collectionAddress;
// rewardTiersAddress to resolve reward tier specifications
address private tiersAddress;
// minProofRequired to deposit of rewards to be eligibile
uint256 private minRequired;
// maxProofAllowed for deposit to be eligibile
uint256 private maxAllowed;
// totalTokensClaimed of all rewards awarded
uint256 private totalTokensClaimed;
// totalTimesClaimed of all successfully claimed rewards
uint256 private totalTimesClaimed;
// totalActiveAccounts count of all currently active addresses
uint256 private totalActiveAccounts;
// Accounts mapping of user loyalty records
mapping(address => Account) private accounts;
/**
* @dev Sparkle Loyalty Rewards Program contract .cTor
* @param _tokenAddress of token used for proof of loyalty rewards
* @param _treasuryAddress of proof of loyalty token reward distribution
* @param _collectionAddress of ethereum account to collect tier upgrade eth
* @param _tiersAddress of the proof of loyalty tier rewards support contract
* @param _timestampAddress of the proof of loyalty timestamp support contract
*/
constructor(address _tokenAddress, address _treasuryAddress, address _collectionAddress, address _tiersAddress, address _timestampAddress)
public
Ownable()
Pausable()
ReentrancyGuard()
{
// Initialize contract internal addresse(s) from params
tokenAddress = _tokenAddress;
treasuryAddress = _treasuryAddress;
collectionAddress = _collectionAddress;
tiersAddress = _tiersAddress;
timestampAddress = _timestampAddress;
// Initialize minimum/maximum allowed deposit limits
minRequired = uint256(1000).mul(10e7);
maxAllowed = uint256(250000).mul(10e7);
}
/**
* @dev Deposit additional tokens to a reward address loyalty balance
* @param _depositAmount of tokens to deposit into a reward address balance
* @return bool indicating the success of the deposit operation (true == success)
*/
function depositLoyalty(uint _depositAmount)
public
whenNotPaused
nonReentrant
returns (bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}1');
// Validate specified value meets minimum requirements
require(_depositAmount >= minRequired, 'Minimum required');
// Determine if caller has approved enough allowance for this deposit
if(IERC20(tokenAddress).allowance(msg.sender, address(this)) < _depositAmount) {
// No, rever informing that deposit amount exceeded allownce amount
revert('Exceeds allowance');
}
// Obtain a storage instsance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Determine if there is an upper deposit cap
if(maxAllowed > 0) {
// Yes, determine if the deposit amount + current balance exceed max deposit cap
if(loyaltyAccount._balance.add(_depositAmount) > maxAllowed || _depositAmount > maxAllowed) {
// Yes, revert informing that the maximum deposit cap has been exceeded
revert('Exceeds cap');
}
}
// Determine if the tier selected is enabled
if(!ISparkleRewardTiers(tiersAddress).getEnabled(loyaltyAccount._tier)) {
// No, then this tier cannot be selected
revert('Invalid tier');
}
// Determine of transfer from caller has succeeded
if(IERC20(tokenAddress).transferFrom(msg.sender, address(this), _depositAmount)) {
// Yes, thend determine if the specified address has a timestamp record
if(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender)) {
// Yes, update callers account balance by deposit amount
loyaltyAccount._balance = loyaltyAccount._balance.add(_depositAmount);
// Reset the callers reward timestamp
_resetTimestamp(msg.sender);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, true);
// Return success
return true;
}
// Determine if a timestamp has been added for caller
if(!ISparkleTimestamp(timestampAddress).addTimestamp(msg.sender)) {
// No, revert indicating there was some kind of error
revert('No timestamp created');
}
// Prepare loyalty account record
loyaltyAccount._address = address(msg.sender);
loyaltyAccount._balance = _depositAmount;
loyaltyAccount._joined = loyaltyAccount._joined.add(1);
// Update global account counter
totalActiveAccounts = totalActiveAccounts.add(1);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, false);
// Return success
return true;
}
// Return failure
return false;
}
/**
* @dev Claim Sparkle Loyalty reward
*/
function claimLoyaltyReward()
public
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate caller has a timestamp and it has matured
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No record');
require(ISparkleTimestamp(timestampAddress).isRewardReady(msg.sender), 'Not mature');
// Obtain the current state of the callers timestamp
(uint256 timeRemaining, bool isReady, uint256 rewardDate) = ISparkleTimestamp(timestampAddress).getTimeRemaining(msg.sender);
// Determine if the callers reward has matured
if(isReady) {
// Value not used but throw unused var warning (cleanup)
rewardDate = 0;
// Yes, then obtain a storage instance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Obtain values required for caculations
uint256 dayCount = (timeRemaining.div(ISparkleTimestamp(timestampAddress).getTimePeriod())).add(1);
uint256 tokenBalance = loyaltyAccount._balance.add(loyaltyAccount._collected);
uint256 rewardRate = ISparkleRewardTiers(tiersAddress).getRate(loyaltyAccount._tier);
uint256 rewardTotal = baseRate.mul(tokenBalance).mul(rewardRate).mul(dayCount).div(10e7).div(10e7);
// Increment collected by reward total
loyaltyAccount._collected = loyaltyAccount._collected.add(rewardTotal);
// Increment total number of times a reward has been claimed
loyaltyAccount._claimed = loyaltyAccount._claimed.add(1);
// Incrememtn total number of times rewards have been collected by all
totalTimesClaimed = totalTimesClaimed.add(1);
// Increment total number of tokens claimed
totalTokensClaimed += rewardTotal;
// Reset the callers timestamp record
_resetTimestamp(msg.sender);
// Emit event log to the block chain for future web3 use
emit RewardClaimedEvent(msg.sender, rewardTotal);
// Return success
return true;
}
// Revert opposed to returning boolean (May or may not return a txreceipt)
revert('Failed claim');
}
/**
* @dev Withdraw the current deposit balance + any earned loyalty rewards
*/
function withdrawLoyalty()
public
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No timestamp2');
// Determine if the account has been locked
if(accounts[msg.sender]._isLocked) {
// Yes, revert informing that this loyalty account has been locked
revert('Locked');
}
// Obtain values needed from account record before zeroing
uint256 joinCount = accounts[msg.sender]._joined;
uint256 collected = accounts[msg.sender]._collected;
uint256 deposit = accounts[msg.sender]._balance;
bool isLocked = accounts[msg.sender]._isLocked;
// Zero out the callers account record
Account storage account = accounts[msg.sender];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
// Preserve account lock even after withdraw (account always locked)
account._isLocked = isLocked;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(msg.sender);
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, msg.sender, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(msg.sender, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected));
}
function returnLoyaltyDeposit(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 deposit = accounts[_rewardAddress]._balance;
Account storage account = accounts[_rewardAddress];
account._balance = 0x0;
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(_rewardAddress, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyDepositWithdrawnEvent(_rewardAddress, deposit);
}
function returnLoyaltyCollected(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 collected = accounts[_rewardAddress]._collected;
Account storage account = accounts[_rewardAddress];
account._collected = 0x0;
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, _rewardAddress, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyCollectedWithdrawnEvent(_rewardAddress, collected);
}
function removeLoyaltyAccount(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 joinCount = accounts[_rewardAddress]._joined;
Account storage account = accounts[_rewardAddress];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
account._isLocked = false;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(_rewardAddress);
emit LoyaltyAccountRemovedEvent(_rewardAddress);
}
/**
* @dev Gets the locked status of the specified address
* @param _loyaltyAddress of account
* @return (bool) indicating locked status
*/
function isLocked(address _loyaltyAddress)
public
view
whenNotPaused
returns (bool)
{
return accounts[_loyaltyAddress]._isLocked;
}
function lockAccount(address _rewardAddress, bool _value)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_rewardAddress != address(0x0), 'Invalid {reward}');
// Validate specified address has timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timstamp');
// Set the specified address' locked status
accounts[_rewardAddress]._isLocked = _value;
// Emit event log to the block chain for future web3 use
emit LockedAccountEvent(_rewardAddress, _value);
}
/**
* @dev Gets the storage address value of the specified address
* @param _loyaltyAddress of account
* @return (address) indicating the address stored calls account record
*/
function getLoyaltyAddress(address _loyaltyAddress)
public
view
whenNotPaused
returns(address)
{
return accounts[_loyaltyAddress]._address;
}
/**
* @dev Get the deposit balance value of specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the balance value
*/
function getDepositBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance;
}
/**
* @dev Get the tokens collected by the specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the tokens collected
*/
function getTokensCollected(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._collected;
}
/**
* @dev Get the total balance (deposit + collected) of tokens
* @param _loyaltyAddress of account
* @return (uint256) indicating total balance
*/
function getTotalBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance.add(accounts[_loyaltyAddress]._collected);
}
/**
* @dev Get the times loyalty has been claimed
* @param _loyaltyAddress of account
* @return (uint256) indicating total time claimed
*/
function getTimesClaimed(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._claimed;
}
/**
* @dev Get total number of times joined
* @param _loyaltyAddress of account
* @return (uint256)
*/
function getTimesJoined(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._joined;
}
/**
* @dev Get time remaining before reward maturity
* @param _loyaltyAddress of account
* @return (uint256, bool) Indicating time remaining/past and boolean indicating maturity
*/
function getTimeRemaining(address _loyaltyAddress)
public
whenNotPaused
returns (uint256, bool, uint256)
{
(uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress);
return (remaining, status, deposit);
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _loyaltyAddress of account
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getRewardTier(address _loyaltyAddress)
public
view whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._tier;
}
/**
* @dev Select reward tier for msg.sender
* @param _tierSelected id of the reward tier interested in purchasing
* @return (bool) indicating failure/success
*/
function selectRewardTier(uint256 _tierSelected)
public
payable
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address has a timestamp
require(accounts[msg.sender]._address == address(msg.sender), 'No timestamp3');
// Validate tier selection
require(accounts[msg.sender]._tier != _tierSelected, 'Already selected');
// Validate that ether was sent with the call
require(msg.value > 0, 'No ether');
// Determine if the specified rate is > than existing rate
if(ISparkleRewardTiers(tiersAddress).getRate(accounts[msg.sender]._tier) >= ISparkleRewardTiers(tiersAddress).getRate(_tierSelected)) {
// No, revert indicating failure
revert('Invalid tier');
}
// Determine if ether transfer for tier upgrade has completed successfully
(bool success, ) = address(collectionAddress).call{value: ISparkleRewardTiers(tiersAddress).getPrice(_tierSelected), gas: gasToSendWithTX}('');
require(success, 'Rate unchanged');
// Update callers rate with the new selected rate
accounts[msg.sender]._tier = _tierSelected;
emit TierSelectedEvent(msg.sender, _tierSelected);
// Return success
return true;
}
function getRewardTiersAddress()
public
view
whenNotPaused
returns(address)
{
return tiersAddress;
}
/**
* @dev Set tier collectionm address
* @param _newAddress of new collection address
* @notice Test(s) not written
*/
function setRewardTiersAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {reward}');
// Set tier rewards contract address
tiersAddress = _newAddress;
emit TiersAddressChanged(_newAddress);
}
function getCollectionAddress()
public
view
whenNotPaused
returns(address)
{
return collectionAddress;
}
/** @notice Test(s) passed
* @dev Set tier collectionm address
* @param _newAddress of new collection address
*/
function setCollectionAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {collection}');
// Set tier collection address
collectionAddress = _newAddress;
emit CollectionAddressChanged(_newAddress);
}
function getTreasuryAddress()
public
view
whenNotPaused
returns(address)
{
return treasuryAddress;
}
/**
* @dev Set treasury address
* @param _newAddress of the treasury address
* @notice Test(s) passed
*/
function setTreasuryAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Validate specified address
require(_newAddress != address(0), "Invalid {treasury}");
// Set current treasury contract address
treasuryAddress = _newAddress;
emit TreasuryAddressChanged(_newAddress);
}
function getTimestampAddress()
public
view
whenNotPaused
returns(address)
{
return timestampAddress;
}
/**
* @dev Set the timestamp address
* @param _newAddress of timestamp address
* @notice Test(s) passed
*/
function setTimestampAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current timestamp contract address
timestampAddress = _newAddress;
emit TimestampAddressChanged(_newAddress);
}
function getTokenAddress()
public
view
whenNotPaused
returns(address)
{
return tokenAddress;
}
/**
* @dev Set the loyalty token address
* @param _newAddress of the new token address
* @notice Test(s) passed
*/
function setTokenAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current token contract address
tokenAddress = _newAddress;
emit TokenAddressChangedEvent(_newAddress);
}
function getSentGasAmount()
public
view
whenNotPaused
returns(uint256)
{
return gasToSendWithTX;
}
function setSentGasAmount(uint256 _amount)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
gasToSendWithTX = _amount;
emit GasSentChanged(_amount);
}
function getBaseRate()
public
view
whenNotPaused
returns(uint256)
{
return baseRate;
}
function setBaseRate(uint256 _newRate)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
baseRate = _newRate;
emit BaseRateChanged(_newRate);
}
/**
* @dev Set the minimum Proof Of Loyalty amount allowed for deposit
* @param _minProof amount for new minimum accepted loyalty reward deposit
* @notice _minProof value is multiplied internally by 10e7. Do not multiply before calling!
*/
function setMinProof(uint256 _minProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate specified minimum is not lower than 1000 tokens
require(_minProof >= 1000, 'Invalid amount');
// Set the current minimum deposit allowed
minRequired = _minProof.mul(10e7);
emit MinProofChanged(minRequired);
}
event MinProofChanged(uint256);
/**
* @dev Get the minimum Proof Of Loyalty amount allowed for deposit
* @return Amount of tokens required for Proof Of Loyalty Rewards
* @notice Test(s) passed
*/
function getMinProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating minimum deposit allowed
return minRequired;
}
/**
* @dev Set the maximum Proof Of Loyalty amount allowed for deposit
* @param _maxProof amount for new maximum loyalty reward deposit
* @notice _maxProof value is multiplied internally by 10e7. Do not multiply before calling!
* @notice Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000)
*/
function setMaxProof(uint256 _maxProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
require(_maxProof >= 2000, 'Invalid amount');
// Set allow maximum deposit
maxAllowed = _maxProof.mul(10e7);
}
/**
* @dev Get the maximum Proof Of Loyalty amount allowed for deposit
* @return Maximum amount of tokens allowed for Proof Of Loyalty deposit
* @notice Test(s) passed
*/
function getMaxProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating current allowed maximum deposit
return maxAllowed;
}
/**
* @dev Get the total number of tokens claimed by all users
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getTotalTokensClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTokensClaimed;
}
/**
* @dev Get total number of times rewards have been claimed for all users
* @return Total number of times rewards have been claimed
*/
function getTotalTimesClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTimesClaimed;
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
*/
function withdrawEth(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0x0), 'Invalid {to}');
// Validate there is ether to withdraw
require(address(this).balance > 0, 'No ether');
// Determine if ether transfer of stored ether has completed successfully
// require(address(_toAddress).call.value(address(this).balance).gas(gasToSendWithTX)(), 'Withdraw failed');
(bool success, ) = address(_toAddress).call{value:address(this).balance, gas: gasToSendWithTX}('');
require(success, 'Withdraw failed');
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _toAddress to receive any stored token balance
*/
function withdrawTokens(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0), "Invalid {to}");
// Validate there are tokens to withdraw
uint256 balance = IERC20(tokenAddress).balanceOf(address(this));
require(balance != 0, "No tokens");
// Validate the transfer of tokens completed successfully
if(IERC20(tokenAddress).transfer(_toAddress, balance)) {
emit TokensWithdrawn(_toAddress, balance);
}
}
/**
* @dev Override loyalty account tier by contract owner
* @param _loyaltyAccount loyalty account address to tier override
* @param _tierSelected reward tier to override current tier value
* @return (bool) indicating success status
*/
function overrideRewardTier(address _loyaltyAccount, uint256 _tierSelected)
public
whenNotPaused
onlyOwner
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_loyaltyAccount != address(0x0), 'Invalid {account}');
// Validate specified address has a timestamp
require(accounts[_loyaltyAccount]._address == address(_loyaltyAccount), 'No timestamp4');
// Update the specified loyalty address tier reward index
accounts[_loyaltyAccount]._tier = _tierSelected;
emit RewardTierChanged(_loyaltyAccount, _tierSelected);
}
/**
* @dev Reset the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm a reset
*/
function _resetTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Reset callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).resetTimestamp(_rewardAddress), 'Reset failed');
emit ResetTimestampEvent(_rewardAddress);
}
/**
* @dev Delete the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm the delete
*/
function _deleteTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}16');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Delete callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).deleteTimestamp(_rewardAddress), 'Delete failed');
emit DeleteTimestampEvent(_rewardAddress);
}
/**
* @dev Event signal: Treasury address updated
*/
event TreasuryAddressChanged(address);
/**
* @dev Event signal: Timestamp address updated
*/
event TimestampAddressChanged(address);
/**
* @dev Event signal: Token address updated
*/
event TokenAddressChangedEvent(address);
/**
* @dev Event signal: Timestamp reset
*/
event ResetTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Timestamp deleted
*/
event DeleteTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Loyalty deposited event
*/
event DepositLoyaltyEvent(address, uint256, bool);
/**
* @dev Event signal: Reward claimed successfully for address
*/
event RewardClaimedEvent(address, uint256);
/**
* @dev Event signal: Loyalty withdrawn
*/
event LoyaltyWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Account locked/unlocked
*/
event LockedAccountEvent(address _rewardAddress, bool _locked);
/**
* @dev Event signal: Loyalty deposit balance withdrawn
*/
event LoyaltyDepositWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty collected balance withdrawn
*/
event LoyaltyCollectedWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty account removed
*/
event LoyaltyAccountRemovedEvent(address);
/**
* @dev Event signal: Gas sent with call.value amount updated
*/
event GasSentChanged(uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TierSelectedEvent(address, uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TiersAddressChanged(address);
/**
* @dev Event signal: Reward tier has been updated
*/
event RewardTierChanged(address, uint256);
/**
* @dev Event signal: Collection address updated
*/
event CollectionAddressChanged(address);
/**
* @dev Event signal: All stored tokens have been removed
*/
event TokensWithdrawn(address, uint256);
/**
* @dev Event signal: Apr base rate has been changed
*/
event BaseRateChanged(uint256);
} | Emit event log to the block chain for future web3 use | emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected));
| 6,070,121 | [
1,
17982,
871,
613,
358,
326,
1203,
2687,
364,
3563,
3311,
23,
999,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3626,
3176,
93,
15006,
1190,
9446,
82,
1133,
12,
3576,
18,
15330,
16,
443,
1724,
18,
1289,
12,
14676,
329,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xdbc61a1685C6F70c11cBb7da70338352b1Fa4d51/sources/DigiDaigakuGiantDragons.sol | * @notice Mints multiple Giant Dragons created with the specified Baby Dragon and Dragon Essence tokens. @dev Throws if `to` address is zero address. @dev Throws if the quantity is zero. @dev Throws if the caller is not a whitelisted minter. @dev Throws if minting would exceed the max supply. @dev <h4>Postconditions:</h4> @dev 1. `quantity` Giant Dragons have been minted to the specified `to` address, where `quantity` is the length of the token id arrays. @dev 2. `quantity` DragonMinted events has been emitted, where `quantity` is the length of the token id arrays. @param to The address of the destination of the Giant Dragons. @param babyDragonTokenIds An array of Baby DragonTokenIds to be used to mint the Giant Dragons. @param dragonEssenceTokenIds An array of DragonEssenceTokenIds to be used to mint the Giant Dragons./ | function mintDragonsBatch(
address to,
uint256[] calldata babyDragonTokenIds,
uint256[] calldata dragonEssenceTokenIds
) external {
_requireMinterIsWhitelisted(_msgSender());
unchecked {
for (uint256 i = 0; i < dragonEssenceTokenIds.length; ++i) {
_mint(to, babyDragonTokenIds[i]);
emit GiantDragonMinted(to, babyDragonTokenIds[i], dragonEssenceTokenIds[i]);
}
}
}
| 15,729,339 | [
1,
49,
28142,
3229,
611,
77,
970,
28425,
7008,
2522,
598,
326,
1269,
605,
24383,
28425,
265,
471,
28425,
265,
512,
1049,
802,
2430,
18,
377,
22435,
309,
1375,
869,
68,
1758,
353,
3634,
1758,
18,
377,
22435,
309,
326,
10457,
353,
3634,
18,
377,
22435,
309,
326,
4894,
353,
486,
279,
26944,
1131,
387,
18,
377,
22435,
309,
312,
474,
310,
4102,
9943,
326,
943,
14467,
18,
377,
411,
76,
24,
34,
3349,
6381,
19814,
76,
24,
34,
377,
404,
18,
1375,
16172,
68,
611,
77,
970,
28425,
7008,
1240,
2118,
312,
474,
329,
358,
326,
1269,
1375,
869,
68,
1758,
16,
1625,
1375,
16172,
68,
353,
326,
769,
434,
326,
1147,
612,
5352,
18,
377,
576,
18,
1375,
16172,
68,
28425,
265,
49,
474,
329,
2641,
711,
2118,
17826,
16,
1625,
1375,
16172,
68,
353,
326,
769,
434,
326,
1147,
612,
5352,
18,
282,
358,
5397,
1021,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
312,
474,
11728,
7008,
4497,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
324,
24383,
11728,
265,
1345,
2673,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
8823,
265,
41,
1049,
802,
1345,
2673,
203,
565,
262,
3903,
288,
203,
3639,
389,
6528,
49,
2761,
2520,
18927,
329,
24899,
3576,
12021,
10663,
203,
203,
3639,
22893,
288,
203,
5411,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
8823,
265,
41,
1049,
802,
1345,
2673,
18,
2469,
31,
965,
77,
13,
288,
203,
7734,
389,
81,
474,
12,
869,
16,
324,
24383,
11728,
265,
1345,
2673,
63,
77,
19226,
203,
7734,
3626,
611,
77,
970,
11728,
265,
49,
474,
329,
12,
869,
16,
324,
24383,
11728,
265,
1345,
2673,
63,
77,
6487,
8823,
265,
41,
1049,
802,
1345,
2673,
63,
77,
19226,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x0240dEBeEe7F019bfe89f752f6aeffF95a11352f/sources/_aave/core-v3/contracts/protocol/libraries/helpers/Errors.sol | 'Invalid risk parameters for the eMode category'
| string public constant INVALID_EMODE_CATEGORY_PARAMS = '21'; | 813,525 | [
1,
11,
1941,
18404,
1472,
364,
326,
425,
2309,
3150,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
533,
1071,
5381,
10071,
67,
3375,
2712,
67,
24847,
67,
16785,
273,
296,
5340,
13506,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "./lib/SafeMath8.sol";
import "./owner/Operator.sol";
import "./interfaces/IOracle.sol";
/*
βββββββ βββββββ ββββββ βββββββ ββββββββ βββββββββββββββ βββ ββββββ ββββ βββ βββββββββββββββ
ββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββ ββββββββββββββββ βββββββββββββββββββ
βββ ββββββββββββββββββββββββββββββββββ ββββββ βββββββββ βββββββββββββββββ ββββββ ββββββ
βββ ββββββββββββββββββββββββββ ββββββ ββββββ ββββββββββββββββββββββββββββββββββ ββββββ
ββββββββββββ ββββββ ββββββ ββββββββ βββ ββββββ βββββββββ ββββββ ββββββββββββββββββββββ
βββββββ βββ ββββββ ββββββ ββββββββ βββ ββββββ ββββββββ ββββββ βββββ βββββββββββββββ
*/
contract Grape is ERC20Burnable, Operator {
using SafeMath8 for uint8;
using SafeMath for uint256;
// Initial distribution for the first 24h genesis pools
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
// Initial distribution for the day 2-5 GRAPE-WETH LP -> GRAPE pool
uint256 public constant INITIAL_GRAPE_POOL_DISTRIBUTION = 21600 ether;
// Distribution for airdrops wallet
uint256 public constant INITIAL_AIRDROP_WALLET_DISTRIBUTION = 1000 ether;
// Have the rewards been distributed to the pools
bool public rewardPoolDistributed = false;
address public grapeOracle;
/**
* @notice Constructs the GRAPE ERC-20 contract.
*/
constructor() public ERC20("Grape Finance", "GRAPE") {
// Mints 1 GRAPE to contract creator for initial pool setup
_mint(msg.sender, 1 ether);
}
function _getGrapePrice() internal view returns (uint256 _grapePrice) {
try IOracle(grapeOracle).consult(address(this), 1e18) returns (uint144 _price) {
return uint256(_price);
} catch {
revert("Grape: failed to fetch GRAPE price from Oracle");
}
}
function setGrapeOracle(address _grapeOracle) public onlyOperator {
require(_grapeOracle != address(0), "oracle address cannot be 0 address");
grapeOracle = _grapeOracle;
}
/**
* @notice Operator mints GRAPE to a recipient
* @param recipient_ The address of recipient
* @param amount_ The amount of GRAPE to mint to
* @return whether the process has been done
*/
function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) {
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override onlyOperator {
super.burnFrom(account, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @notice distribute to reward pool (only once)
*/
function distributeReward(
address _genesisPool,
address _grapePool,
address _airdropWallet
) external onlyOperator {
require(!rewardPoolDistributed, "only can distribute once");
require(_genesisPool != address(0), "!_genesisPool");
require(_grapePool != address(0), "!_grapePool");
require(_airdropWallet != address(0), "!_airdropWallet");
rewardPoolDistributed = true;
_mint(_genesisPool, INITIAL_GENESIS_POOL_DISTRIBUTION);
_mint(_grapePool, INITIAL_GRAPE_POOL_DISTRIBUTION);
_mint(_airdropWallet, INITIAL_AIRDROP_WALLET_DISTRIBUTION);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
_token.transfer(_to, _amount);
}
}
| Initial distribution for the first 24h genesis pools Initial distribution for the day 2-5 GRAPE-WETH LP -> GRAPE pool Distribution for airdrops wallet Have the rewards been distributed to the pools | contract Grape is ERC20Burnable, Operator {
using SafeMath8 for uint8;
using SafeMath for uint256;
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
uint256 public constant INITIAL_GRAPE_POOL_DISTRIBUTION = 21600 ether;
uint256 public constant INITIAL_AIRDROP_WALLET_DISTRIBUTION = 1000 ether;
bool public rewardPoolDistributed = false;
address public grapeOracle;
constructor() public ERC20("Grape Finance", "GRAPE") {
_mint(msg.sender, 1 ether);
}
function _getGrapePrice() internal view returns (uint256 _grapePrice) {
try IOracle(grapeOracle).consult(address(this), 1e18) returns (uint144 _price) {
return uint256(_price);
revert("Grape: failed to fetch GRAPE price from Oracle");
}
}
function _getGrapePrice() internal view returns (uint256 _grapePrice) {
try IOracle(grapeOracle).consult(address(this), 1e18) returns (uint144 _price) {
return uint256(_price);
revert("Grape: failed to fetch GRAPE price from Oracle");
}
}
} catch {
function setGrapeOracle(address _grapeOracle) public onlyOperator {
require(_grapeOracle != address(0), "oracle address cannot be 0 address");
grapeOracle = _grapeOracle;
}
function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) {
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override onlyOperator {
super.burnFrom(account, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function distributeReward(
address _genesisPool,
address _grapePool,
address _airdropWallet
) external onlyOperator {
require(!rewardPoolDistributed, "only can distribute once");
require(_genesisPool != address(0), "!_genesisPool");
require(_grapePool != address(0), "!_grapePool");
require(_airdropWallet != address(0), "!_airdropWallet");
rewardPoolDistributed = true;
_mint(_genesisPool, INITIAL_GENESIS_POOL_DISTRIBUTION);
_mint(_grapePool, INITIAL_GRAPE_POOL_DISTRIBUTION);
_mint(_airdropWallet, INITIAL_AIRDROP_WALLET_DISTRIBUTION);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
_token.transfer(_to, _amount);
}
}
| 12,561,110 | [
1,
4435,
7006,
364,
326,
1122,
4248,
76,
21906,
16000,
10188,
7006,
364,
326,
2548,
576,
17,
25,
611,
2849,
1423,
17,
59,
1584,
44,
511,
52,
317,
611,
2849,
1423,
2845,
17547,
364,
279,
6909,
16703,
9230,
21940,
326,
283,
6397,
2118,
16859,
358,
326,
16000,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
10812,
347,
353,
4232,
39,
3462,
38,
321,
429,
16,
11097,
288,
203,
565,
1450,
14060,
10477,
28,
364,
2254,
28,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
16652,
41,
15664,
67,
20339,
67,
31375,
273,
4248,
713,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
24554,
1423,
67,
20339,
67,
31375,
273,
576,
2313,
713,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
37,
7937,
18768,
67,
59,
1013,
15146,
67,
31375,
273,
4336,
225,
2437,
31,
203,
203,
565,
1426,
1071,
19890,
2864,
1669,
11050,
273,
629,
31,
203,
203,
565,
1758,
1071,
3087,
347,
23601,
31,
203,
203,
203,
203,
203,
565,
3885,
1435,
1071,
4232,
39,
3462,
2932,
14571,
347,
9458,
1359,
3113,
315,
24554,
1423,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
404,
225,
2437,
1769,
27699,
565,
289,
203,
203,
565,
445,
389,
588,
14571,
347,
5147,
1435,
2713,
1476,
1135,
261,
11890,
5034,
389,
2752,
347,
5147,
13,
288,
203,
3639,
775,
1665,
16873,
12,
2752,
347,
23601,
2934,
8559,
406,
12,
2867,
12,
2211,
3631,
404,
73,
2643,
13,
1135,
261,
11890,
25339,
389,
8694,
13,
288,
203,
5411,
327,
2254,
5034,
24899,
8694,
1769,
203,
5411,
15226,
2932,
14571,
347,
30,
2535,
358,
2158,
611,
2849,
1423,
6205,
628,
28544,
8863,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
588,
14571,
347,
5147,
1435,
2713,
1476,
1135,
261,
2
] |
/*
SPDX-License-Identifier: MIT
*/
pragma solidity >0.8.0;
import "./buildingGeneration.sol";
abstract contract marketplace is buildingGeneration {
// Declare all events here
event resourceListed(uint item, uint quantity, uint price, address owner);
event buildingListed(uint price, address owner);
event resourceLotteryBegin(uint entryFee);
event buildingLotteryBegin(uint entryFee);
event resourceSold(uint price, address to, address from);
event buildingSold(uint price, address to, address from);
event resourceLotteryWon(address winner);
event buildingLotteryWon(address winner);
// Declare all variables here
uint private winningIndex;
// Declare all modifiers
modifier enoughResources(address _address, uint16 _biome, uint8 _rarity, uint _quantity) {
uint counter = 0;
for(uint i = 0; i < Resources.length; i++) {
if (resourceToOwner[i] == msg.sender) {
if (Resources[i].biome == _biome && Resources[i].rarity == _rarity) {
counter++;
}
}
}
require(counter >= _quantity);
_;
}
// Declare all functions here
function _randomIndex() internal view returns (uint) {
// TODO: use an oracle to get a random number
}
function listItem(uint _quantity, uint _price, uint16 _biome, uint8 _rarity, address _owner) public enoughResources(_owner, _biome, _rarity, _quantity) {
// TODO: Puts the item in escrow, where a person can pay the address _price tokens and receive _item
}
}
| TODO: Puts the item in escrow, where a person can pay the address _price tokens and receive _item | function listItem(uint _quantity, uint _price, uint16 _biome, uint8 _rarity, address _owner) public enoughResources(_owner, _biome, _rarity, _quantity) {
}
| 15,860,105 | [
1,
6241,
30,
4399,
87,
326,
761,
316,
2904,
492,
16,
1625,
279,
6175,
848,
8843,
326,
1758,
389,
8694,
2430,
471,
6798,
389,
1726,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
19859,
12,
11890,
389,
16172,
16,
2254,
389,
8694,
16,
2254,
2313,
389,
13266,
1742,
16,
2254,
28,
389,
86,
20498,
16,
1758,
389,
8443,
13,
1071,
7304,
3805,
24899,
8443,
16,
389,
13266,
1742,
16,
389,
86,
20498,
16,
389,
16172,
13,
288,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.