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 |
---|---|---|---|---|---|---|
/**
RFM: Rare Fish Market
A coin that could be used to buy the rarest of fish,
the most magestic, sublime, elevated fish
that not even the wealthy can find amongst the market,
these fish have over the past months doubled, tripled, 10x, 100x, 500x
This token serves as a overall benchmark of the Rare Fish Market.
,
/( /:./\
,_/:`-/::/::/\_ ,
|:|::/::/::/::;'( ,,
|:|:/::/::/:;'::,':(.( ,
_,-'"HHHHH"""HHoo--.::::,-:(,----..._
,-"HHHb "HHHHb HHHHb HHHoo-.::::::::::-.
,' "HHHb "HHHHb "HHHH HHHHH Hoo::::::::::. _,.-::`.
,' "HH`. "HHHH HHHHb "HHHH "HHHb`-:::::::. _.-:::::::;'
/ ,-. : HHHH "HHHH HHHH HHHH Hoo::::; _,-:::::::::;'
,' `-' : HHHH HHHH "HHH "HHH "HHHH-:._,o:::::::::::;'
/ : HHHH __HHHP...........HHH HHHF HHH:::::::;:;'
/_ ; _,-::::::.:::::::::::::''HH HHH "HH::::::::(
(_"-., / : :.::.:.::::::::::,d HHH "HH HH::::::::::.
(,-' / :.::.:::.::::::;'HHH "HH HH,::"-.H::::::::::::.
". ,' : :.:::.::::::;' "HH HH _H-:::) `-::::::::::::.
`-.___,-' `-.:::::,--'" "H HH,-::::::/ "--.::::::::.
"""---..__________________,-------'::::::::;/ """---'
\::.:---. `::::::::::;'
\::::::| `::;-'""
`.::::|
`.::|
`-'
Max transaction 1%, Max wallet 2% - Whale Protection until coin stable.
LP Locked and Contract Renounced after restrictions lifted.
**/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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");
_;
}
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);
}
}
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);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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_;
}
/**
* @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;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// 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);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract RFM is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Rare Fish Market", unicode"RFM") {
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 = 7;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 0;
uint256 totalSupply = 100_000_000 * 1e18;
maxTransactionAmount = 1_000_000 * 1e18;
maxWallet = 2_000_000 * 1e18;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xa91C46e6B5728FD8caec077d3063C0b3Ef5a2cE2); // set as marketing wallet
devWallet = address(0xa91C46e6B5728FD8caec077d3063C0b3Ef5a2cE2); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function StartTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000 ) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function 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 <= 10, "Must keep fees at 10% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success, ) = address(devWallet).call{value: ethForDev}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | set as marketing wallet
| marketingWallet = address(0xa91C46e6B5728FD8caec077d3063C0b3Ef5a2cE2); | 10,132,115 | [
1,
542,
487,
13667,
310,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
13667,
310,
16936,
273,
1758,
12,
20,
6995,
12416,
39,
8749,
73,
26,
38,
10321,
6030,
16894,
28,
5353,
557,
20,
4700,
72,
5082,
4449,
39,
20,
70,
23,
41,
74,
25,
69,
22,
71,
41,
22,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0x413E395b10Be6F39f2AA0d80EEC48EDB88738aC4/sources/contracts/utils/GoodDollarMintBurnWrapper.sol | basis points relative to token supply daily limit
| uint32 bpsPerDay; | 16,316,123 | [
1,
23774,
3143,
3632,
358,
1147,
14467,
18872,
1800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
11890,
1578,
324,
1121,
2173,
4245,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0xc00210F3Dd9618D205cC642a4d1Ad7bDc3a34A6A/sources/project_/contracts/Pool.sol | Withdraws the principal for non-winners | strategy.redeem(inboundToken, payout, _minAmount, disableRewardTokenClaim);
| 16,322,417 | [
1,
1190,
9446,
87,
326,
8897,
364,
1661,
17,
8082,
9646,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
6252,
18,
266,
24903,
12,
267,
3653,
1345,
16,
293,
2012,
16,
389,
1154,
6275,
16,
4056,
17631,
1060,
1345,
9762,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
contract YieldToken is Initializable, ERC20CappedUpgradeable {
using SafeMathUpgradeable for uint256;
uint256 public constant BASE_RATE = 10000 ether; // 10,000 $SPLOOT each day
uint256 public constant INITIAL_ISSUANCE = 0 ether; // 0 $SPLOOT
uint256 constant PRE_MINT_PERCENTAGE = 2;
IERC721Upgradeable public CHEEKY_CORGI;
// Monday, December 08, 2021 12:00:00 AM
uint256 public constant START = 1638921600;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastUpdate;
// Events
event RewardPaid(address indexed user, uint256 reward);
modifier onlyCC() {
require(
msg.sender == address(CHEEKY_CORGI),
"YieldToken: Only CheekyCorgi can call this"
);
_;
}
function initialize(address _cheekyCorgi, uint256 maxSupply, address _owner) external initializer {
__ERC20_init("SPLOOT", "SPLOOT");
__ERC20Capped_init(maxSupply);
CHEEKY_CORGI = IERC721Upgradeable(_cheekyCorgi);
// premint x% to the owner
_mint(_owner, maxSupply.mul(PRE_MINT_PERCENTAGE).div(100));
}
/// @dev get larger value of a and b
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/// @dev called when minting many NFTs
/// @dev NOT REQUIRED
/// updated_amount = (balanceOf(user) * base_rate * delta / 86400) + amount * initial rate
function updateRewardOnMint(address _user, uint256 _amount) external onlyCC {
uint256 time = max(block.timestamp, START);
uint256 timerUser = lastUpdate[_user];
if (timerUser > 0) {
if (time >= timerUser) {
rewards[_user] = rewards[_user].add(
CHEEKY_CORGI
.balanceOf(_user)
.mul(BASE_RATE.mul((time.sub(timerUser))))
.div(86400)
.add(_amount.mul(INITIAL_ISSUANCE))
);
}
} else {
rewards[_user] = rewards[_user].add(_amount.mul(INITIAL_ISSUANCE));
}
if (lastUpdate[_user] < time) {
lastUpdate[_user] = time;
}
}
// called on transfers
function updateReward(address _from, address _to) external onlyCC {
uint256 time = max(block.timestamp, START);
uint256 timerFrom = lastUpdate[_from];
if (timerFrom > 0 && time >= timerFrom) {
rewards[_from] += CHEEKY_CORGI
.balanceOf(_from)
.mul(BASE_RATE.mul((time.sub(timerFrom))))
.div(86400);
}
if (lastUpdate[_from] < time) {
lastUpdate[_from] = time;
}
if (_to != address(0)) {
uint256 timerTo = lastUpdate[_to];
if (timerTo > 0 && time >= timerTo) {
rewards[_to] += CHEEKY_CORGI
.balanceOf(_to)
.mul(BASE_RATE.mul((time.sub(timerTo))))
.div(86400);
}
if (lastUpdate[_to] < time) {
lastUpdate[_to] = time;
}
}
}
function getReward(address _to) external onlyCC {
uint256 reward = rewards[_to];
if (reward > 0) {
rewards[_to] = 0;
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
}
function burn(address _from, uint256 _amount) external onlyCC {
_burn(_from, _amount);
}
function getTotalClaimable(address _user) external view returns (uint256) {
uint256 time = max(block.timestamp, START);
uint256 pending = 0;
if (time > lastUpdate[_user]) {
pending = CHEEKY_CORGI
.balanceOf(_user)
.mul(BASE_RATE.mul((time.sub(lastUpdate[_user]))))
.div(86400);
}
return rewards[_user] + pending;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
function __ERC20Capped_init(uint256 cap_) internal initializer {
__Context_init_unchained();
__ERC20Capped_init_unchained(cap_);
}
function __ERC20Capped_init_unchained(uint256 cap_) internal initializer {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_mint}.
*/
function _mint(address account, uint256 amount) internal virtual override {
require(ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | @dev called when minting many NFTs @dev NOT REQUIRED updated_amount = (balanceOf(user) * base_rate * delta / 86400) + amount * initial rate | function updateRewardOnMint(address _user, uint256 _amount) external onlyCC {
uint256 time = max(block.timestamp, START);
uint256 timerUser = lastUpdate[_user];
if (timerUser > 0) {
if (time >= timerUser) {
rewards[_user] = rewards[_user].add(
CHEEKY_CORGI
.balanceOf(_user)
.mul(BASE_RATE.mul((time.sub(timerUser))))
.div(86400)
.add(_amount.mul(INITIAL_ISSUANCE))
);
}
rewards[_user] = rewards[_user].add(_amount.mul(INITIAL_ISSUANCE));
}
if (lastUpdate[_user] < time) {
lastUpdate[_user] = time;
}
}
| 10,333,281 | [
1,
11777,
1347,
312,
474,
310,
4906,
423,
4464,
87,
225,
4269,
15810,
3526,
67,
8949,
273,
261,
12296,
951,
12,
1355,
13,
225,
1026,
67,
5141,
225,
3622,
342,
21451,
13,
397,
3844,
225,
2172,
4993,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
17631,
1060,
1398,
49,
474,
12,
2867,
389,
1355,
16,
2254,
5034,
389,
8949,
13,
3903,
1338,
6743,
288,
203,
3639,
2254,
5034,
813,
273,
943,
12,
2629,
18,
5508,
16,
10485,
1769,
203,
3639,
2254,
5034,
5441,
1299,
273,
1142,
1891,
63,
67,
1355,
15533,
203,
3639,
309,
261,
12542,
1299,
405,
374,
13,
288,
203,
5411,
309,
261,
957,
1545,
5441,
1299,
13,
288,
203,
7734,
283,
6397,
63,
67,
1355,
65,
273,
283,
6397,
63,
67,
1355,
8009,
1289,
12,
203,
10792,
14274,
11325,
61,
67,
9428,
13797,
203,
13491,
263,
12296,
951,
24899,
1355,
13,
203,
13491,
263,
16411,
12,
8369,
67,
24062,
18,
16411,
12443,
957,
18,
1717,
12,
12542,
1299,
3719,
3719,
203,
13491,
263,
2892,
12,
28,
1105,
713,
13,
203,
13491,
263,
1289,
24899,
8949,
18,
16411,
12,
28497,
67,
25689,
57,
4722,
3719,
203,
7734,
11272,
203,
5411,
289,
203,
5411,
283,
6397,
63,
67,
1355,
65,
273,
283,
6397,
63,
67,
1355,
8009,
1289,
24899,
8949,
18,
16411,
12,
28497,
67,
25689,
57,
4722,
10019,
203,
3639,
289,
203,
3639,
309,
261,
2722,
1891,
63,
67,
1355,
65,
411,
813,
13,
288,
203,
5411,
1142,
1891,
63,
67,
1355,
65,
273,
813,
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
] |
./full_match/80001/0xa405b1810277e95Df44B6573420ED30C55492638/sources/contracts/pub-founders-stake-Legendary.sol | Constructor function to set the rewards token and the NFT collection addresses | constructor(IERC721 _nftCollection, IERC20 _rewardsToken, uint256 _minID, uint256 _maxID) {
nftCollection = _nftCollection;
rewardsToken = _rewardsToken;
minID = _minID;
maxID = _maxID;
deployer = msg.sender;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 871,858 | [
1,
6293,
445,
358,
444,
326,
283,
6397,
1147,
471,
326,
423,
4464,
1849,
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,
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,
377,
3885,
12,
45,
654,
39,
27,
5340,
389,
82,
1222,
2532,
16,
467,
654,
39,
3462,
389,
266,
6397,
1345,
16,
2254,
5034,
389,
1154,
734,
16,
2254,
5034,
389,
1896,
734,
13,
288,
203,
3639,
290,
1222,
2532,
273,
389,
82,
1222,
2532,
31,
203,
3639,
283,
6397,
1345,
273,
389,
266,
6397,
1345,
31,
203,
3639,
1131,
734,
273,
389,
1154,
734,
31,
203,
3639,
943,
734,
273,
389,
1896,
734,
31,
203,
203,
3639,
7286,
264,
273,
1234,
18,
15330,
31,
203,
7734,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x602f47c53fbd3D6F6783F26E01623cCfd53268D0/sources/main-contract/main-contract/XUSDPrime.sol | ─── Struct To Store Details Of The Latest Security Audit ──────────────────── | struct SecurityAudit {
uint256 blockNumber;
uint256 timestamp;
}
| 4,787,627 | [
1,
163,
247,
227,
163,
247,
227,
163,
247,
227,
7362,
2974,
4994,
21897,
8031,
1021,
29830,
6036,
12975,
225,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
6036,
10832,
288,
203,
3639,
2254,
5034,
1203,
1854,
31,
203,
3639,
2254,
5034,
2858,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: 0x26CB3641aaA43911f1D4cB2ce544eb652AAc7c47
//Contract name: CrystalToken
//Balance: 0 Ether
//Verification Date: 2/10/2018
//Transacion Count: 2633
// CODE STARTS HERE
pragma solidity ^0.4.19;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic
{
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic
{
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Contract Ownable (defines a contract with an owner)
//------------------------------------------------------------------------------------------------------------
contract Ownable
{
/**
* @dev Address of the current owner
*/
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// Constructor. Set the original `owner` of the contract to the sender account.
function Ownable() public
{
owner = msg.sender;
}
// Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
/** 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 public
{
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// ------------------------------------------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath
{
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract SafeBasicToken is ERC20Basic
{
// Use safemath for math operations
using SafeMath for uint256;
// Maps each address to its current balance
mapping(address => uint256) balances;
// List of admins that can transfer tokens also during the ICO
mapping(address => bool) public admin;
// List of addresses that can receive tokens also during the ICO
mapping(address => bool) public receivable;
// Specifies whether the tokens are locked(ICO is running) - Tokens cannot be transferred during the ICO
bool public locked;
// Checks the size of the message to avoid attacks
modifier onlyPayloadSize(uint size)
{
assert(msg.data.length >= size + 4);
_;
}
/** Transfer tokens to the specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool)
{
require(_to != address(0));
require(!locked || admin[msg.sender] == true || receivable[_to] == true);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/** Get the balance of the specified address.
* @param _owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256)
{
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 SafeStandardToken is ERC20, SafeBasicToken
{
/** Map address => (address => value)
* allowed[_owner][_spender] represents the amount of tokens the _spender can use on behalf of the _owner
*/
mapping(address => mapping(address => uint256)) allowed;
/** Return the allowance of the _spender on behalf of the _owner
* @param _owner address The address which owns the funds.
* @param _spender address The address which will be allowed to spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/** Allow the _spender to spend _value tokens on behalf of msg.sender.
* To avoid race condition, the current allowed amount must be first set to 0 through a different transaction.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool)
{
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/** Increase the allowance for _spender by _addedValue (to be use when allowed[_spender] > 0)
*/
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;
}
/** Decrease the allowance for _spender by _subtractedValue. Set it to 0 if _subtractedValue is less then the current allowance
*/
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;
}
/** Transfer tokens on behalf of _from to _to (if allowed)
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
// Main contract
contract CrystalToken is SafeStandardToken, Ownable
{
using SafeMath for uint256;
string public constant name = "CrystalToken";
string public constant symbol = "CYL";
uint256 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 28000000 * (10 ** uint256(decimals));
// Struct representing information of a single round
struct Round
{
uint256 startTime; // Timestamp of the start of the round
uint256 endTime; // Timestamp of the end of the round
uint256 availableTokens; // Number of tokens available in this round
uint256 maxPerUser; // Number of maximum tokens per user
uint256 rate; // Number of token per wei in this round
mapping(address => uint256) balances; // Balances of the users in this round
}
// Array containing information of all the rounds
Round[5] rounds;
// Address where funds are collected
address public wallet;
// Amount of collected money in wei
uint256 public weiRaised;
// Current round index
uint256 public runningRound;
// Constructor
function CrystalToken(address _walletAddress) public
{
wallet = _walletAddress;
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
rounds[0] = Round(1519052400, 1519138800, 250000 * (10 ** 18), 200 * (10 ** 18), 2000); // 19 Feb 2018 - 15.00 GMT
rounds[1] = Round(1519398000, 1519484400, 1250000 * (10 ** 18), 400 * (10 ** 18), 1333); // 23 Feb 2018 - 15.00 GMT
rounds[2] = Round(1519657200, 1519743600, 1500000 * (10 ** 18), 1000 * (10 ** 18), 1000); // 26 Feb 2018 - 15.00 GMT
rounds[3] = Round(1519830000, 1519916400, 2000000 * (10 ** 18), 1000 * (10 ** 18), 800); // 28 Feb 2018 - 15.00 GMT
rounds[4] = Round(1520262000, 1520348400, 2000000 * (10 ** 18), 2000 * (10 ** 18), 667); // 5 Mar 2018 - 15.00 GMT
// Set the owner as an admin
admin[msg.sender] = true;
// Lock the tokens for the ICO
locked = true;
// Set the current round to 100 (no round)
runningRound = uint256(0);
}
/** Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// Rate change event
event RateChanged(address indexed owner, uint round, uint256 old_rate, uint256 new_rate);
// Fallback function, used to buy token
// If ETH are sent to the contract address, without any additional data, this function is called
function() public payable
{
// Take the address of the buyer
address beneficiary = msg.sender;
// Check that the sender is not the 0 address
require(beneficiary != 0x0);
// Check that sent ETH in wei is > 0
uint256 weiAmount = msg.value;
require(weiAmount != 0);
// Get the current round (100 if there is no open round)
uint256 roundIndex = runningRound;
// Check if there is a running round
require(roundIndex != uint256(100));
// Get the information of the current round
Round storage round = rounds[roundIndex];
// Calculate the token amount to sell. Exceeding amount will not generate tokens
uint256 tokens = weiAmount.mul(round.rate);
uint256 maxPerUser = round.maxPerUser;
uint256 remaining = maxPerUser - round.balances[beneficiary];
if(remaining < tokens)
tokens = remaining;
// Check if the tokens can be sold
require(areTokensBuyable(roundIndex, tokens));
// Reduce the number of available tokens in the round (fails if there are no more available tokens)
round.availableTokens = round.availableTokens.sub(tokens);
// Add the number of tokens to the current user's balance of this round
round.balances[msg.sender] = round.balances[msg.sender].add(tokens);
// Transfer the amount of token to the buyer
balances[owner] = balances[owner].sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
Transfer(owner, beneficiary, tokens);
// Raise the event of token purchase
TokenPurchase(beneficiary, beneficiary, weiAmount, tokens);
// Update the number of collected money
weiRaised = weiRaised.add(weiAmount);
// Transfer funds to the wallet
wallet.transfer(msg.value);
}
/** Check if there is an open round and if there are enough tokens available for current phase and for the sender
* @param _roundIndex index of the current round
* @param _tokens number of requested tokens
*/
function areTokensBuyable(uint _roundIndex, uint256 _tokens) internal constant returns (bool)
{
uint256 current_time = block.timestamp;
Round storage round = rounds[_roundIndex];
return (
_tokens > 0 && // Check that the user can still buy tokens
round.availableTokens >= _tokens && // Check that there are still available tokens
current_time >= round.startTime && // Check that the current timestamp is after the start of the round
current_time <= round.endTime // Check that the current timestamp is before the end of the round
);
}
// Return the current number of unsold tokens
function tokenBalance() constant public returns (uint256)
{
return balanceOf(owner);
}
event Burn(address burner, uint256 value);
/** Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner
{
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/** Mint a specific amount of tokens.
* @param _value The amount of token to be minted.
*/
function mint(uint256 _value) public onlyOwner
{
totalSupply = totalSupply.add(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
}
// Functions to set the features of each round (only for the owner) and of the whole ICO
// ----------------------------------------------------------------------------------------
function setTokensLocked(bool _value) onlyOwner public
{
locked = _value;
}
/** Set the current round index
* @param _roundIndex the new round index to set
*/
function setRound(uint256 _roundIndex) public onlyOwner
{
runningRound = _roundIndex;
}
function setAdmin(address _addr, bool _value) onlyOwner public
{
admin[_addr] = _value;
}
function setReceivable(address _addr, bool _value) onlyOwner public
{
receivable[_addr] = _value;
}
function setRoundStart(uint _round, uint256 _value) onlyOwner public
{
require(_round >= 0 && _round < rounds.length);
rounds[_round].startTime = _value;
}
function setRoundEnd(uint _round, uint256 _value) onlyOwner public
{
require(_round >= 0 && _round < rounds.length);
rounds[_round].endTime = _value;
}
function setRoundAvailableToken(uint _round, uint256 _value) onlyOwner public
{
require(_round >= 0 && _round < rounds.length);
rounds[_round].availableTokens = _value;
}
function setRoundMaxPerUser(uint _round, uint256 _value) onlyOwner public
{
require(_round >= 0 && _round < rounds.length);
rounds[_round].maxPerUser = _value;
}
function setRoundRate(uint _round, uint256 _round_usd_cents, uint256 _ethvalue_usd) onlyOwner public
{
require(_round >= 0 && _round < rounds.length);
uint256 rate = _ethvalue_usd * 100 / _round_usd_cents;
uint256 oldRate = rounds[_round].rate;
rounds[_round].rate = rate;
RateChanged(msg.sender, _round, oldRate, rounds[_round].rate);
}
// ----------------------------------------------------------------------------------------
// Functions to get the features of each round
// ----------------------------------------------------------------------------------------
function getRoundUserBalance(uint _round, address _user) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].balances[_user];
}
function getRoundStart(uint _round) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].startTime;
}
function getRoundEnd(uint _round) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].endTime;
}
function getRoundAvailableToken(uint _round) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].availableTokens;
}
function getRoundMaxPerUser(uint _round) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].maxPerUser;
}
function getRoundRate(uint _round) public constant returns (uint256)
{
require(_round >= 0 && _round < rounds.length);
return rounds[_round].rate;
}
// ----------------------------------------------------------------------------------------
}
| Fallback function, used to buy token If ETH are sent to the contract address, without any additional data, this function is called Take the address of the buyer Check that the sender is not the 0 address Check that sent ETH in wei is > 0 Get the current round (100 if there is no open round) Check if there is a running round Get the information of the current round Calculate the token amount to sell. Exceeding amount will not generate tokens Check if the tokens can be sold Reduce the number of available tokens in the round (fails if there are no more available tokens) Add the number of tokens to the current user's balance of this round Transfer the amount of token to the buyer Raise the event of token purchase Update the number of collected money Transfer funds to the wallet | function() public payable
{
address beneficiary = msg.sender;
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
require(weiAmount != 0);
uint256 roundIndex = runningRound;
require(roundIndex != uint256(100));
Round storage round = rounds[roundIndex];
uint256 tokens = weiAmount.mul(round.rate);
uint256 maxPerUser = round.maxPerUser;
uint256 remaining = maxPerUser - round.balances[beneficiary];
if(remaining < tokens)
tokens = remaining;
require(areTokensBuyable(roundIndex, tokens));
round.availableTokens = round.availableTokens.sub(tokens);
round.balances[msg.sender] = round.balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
Transfer(owner, beneficiary, tokens);
TokenPurchase(beneficiary, beneficiary, weiAmount, tokens);
weiRaised = weiRaised.add(weiAmount);
wallet.transfer(msg.value);
}
| 5,513,819 | [
1,
12355,
445,
16,
1399,
358,
30143,
1147,
971,
512,
2455,
854,
3271,
358,
326,
6835,
1758,
16,
2887,
1281,
3312,
501,
16,
333,
445,
353,
2566,
17129,
326,
1758,
434,
326,
27037,
2073,
716,
326,
5793,
353,
486,
326,
374,
1758,
2073,
716,
3271,
512,
2455,
316,
732,
77,
353,
405,
374,
968,
326,
783,
3643,
261,
6625,
309,
1915,
353,
1158,
1696,
3643,
13,
2073,
309,
1915,
353,
279,
3549,
3643,
968,
326,
1779,
434,
326,
783,
3643,
9029,
326,
1147,
3844,
358,
357,
80,
18,
1312,
5288,
310,
3844,
903,
486,
2103,
2430,
2073,
309,
326,
2430,
848,
506,
272,
1673,
24614,
326,
1300,
434,
2319,
2430,
316,
326,
3643,
261,
6870,
87,
309,
1915,
854,
1158,
1898,
2319,
2430,
13,
1436,
326,
1300,
434,
2430,
358,
326,
783,
729,
1807,
11013,
434,
333,
3643,
12279,
326,
3844,
434,
1147,
358,
326,
27037,
20539,
326,
871,
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,
1435,
1071,
8843,
429,
203,
565,
288,
203,
3639,
1758,
27641,
74,
14463,
814,
273,
1234,
18,
15330,
31,
203,
203,
3639,
2583,
12,
70,
4009,
74,
14463,
814,
480,
374,
92,
20,
1769,
203,
203,
3639,
2254,
5034,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
3639,
2583,
12,
1814,
77,
6275,
480,
374,
1769,
203,
203,
3639,
2254,
5034,
3643,
1016,
273,
3549,
11066,
31,
203,
203,
3639,
2583,
12,
2260,
1016,
480,
2254,
5034,
12,
6625,
10019,
203,
203,
3639,
11370,
2502,
3643,
273,
21196,
63,
2260,
1016,
15533,
203,
203,
3639,
2254,
5034,
2430,
273,
732,
77,
6275,
18,
16411,
12,
2260,
18,
5141,
1769,
203,
3639,
2254,
5034,
943,
2173,
1299,
273,
3643,
18,
1896,
2173,
1299,
31,
203,
3639,
2254,
5034,
4463,
273,
943,
2173,
1299,
300,
3643,
18,
70,
26488,
63,
70,
4009,
74,
14463,
814,
15533,
203,
3639,
309,
12,
17956,
411,
2430,
13,
203,
5411,
2430,
273,
4463,
31,
203,
203,
3639,
2583,
12,
834,
5157,
38,
9835,
429,
12,
2260,
1016,
16,
2430,
10019,
203,
203,
3639,
3643,
18,
5699,
5157,
273,
3643,
18,
5699,
5157,
18,
1717,
12,
7860,
1769,
203,
203,
3639,
3643,
18,
70,
26488,
63,
3576,
18,
15330,
65,
273,
3643,
18,
70,
26488,
63,
3576,
18,
15330,
8009,
1289,
12,
7860,
1769,
203,
203,
3639,
324,
26488,
63,
8443,
65,
273,
324,
26488,
63,
8443,
8009,
1717,
12,
7860,
1769,
203,
3639,
324,
26488,
63,
70,
4009,
74,
14463,
814,
65,
273,
324,
26488,
63,
70,
2
] |
./partial_match/1/0x37699B0368337C5eA58498446e45D4B45dEdd956/sources/WanFarm.sol | * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation @dev Admin function for new implementation to accept it's role as implementation @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is pendingImplementation and pendingImplementation ≠ address(0) | function _acceptImplementation() public returns (uint) {
if (msg.sender != pendingWanFarmImplementation || pendingWanFarmImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
address oldPendingImplementation = pendingWanFarmImplementation;
wanFarmImplementation = pendingWanFarmImplementation;
pendingWanFarmImplementation = address(0);
emit NewImplementation(oldImplementation, wanFarmImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingWanFarmImplementation);
return uint(Error.NO_ERROR);
}
| 2,804,462 | [
1,
26391,
394,
4471,
434,
532,
337,
1539,
18,
1234,
18,
15330,
1297,
506,
4634,
13621,
225,
7807,
445,
364,
394,
4471,
358,
2791,
518,
1807,
2478,
487,
4471,
327,
2254,
374,
33,
4768,
16,
3541,
279,
5166,
261,
5946,
1068,
13289,
18,
18281,
364,
3189,
13176,
2073,
4894,
353,
4634,
13621,
471,
4634,
13621,
225,
163,
236,
259,
1758,
12,
20,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
9436,
13621,
1435,
1071,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
4634,
59,
304,
42,
4610,
13621,
747,
4634,
59,
304,
42,
4610,
13621,
422,
1758,
12,
20,
3719,
288,
203,
5411,
327,
2321,
12,
668,
18,
2124,
28383,
16,
13436,
966,
18,
21417,
67,
25691,
67,
9883,
7618,
2689,
67,
15140,
67,
10687,
1769,
203,
3639,
289,
203,
203,
3639,
1758,
1592,
8579,
13621,
273,
4634,
59,
304,
42,
4610,
13621,
31,
203,
203,
3639,
341,
304,
42,
4610,
13621,
273,
4634,
59,
304,
42,
4610,
13621,
31,
203,
203,
3639,
4634,
59,
304,
42,
4610,
13621,
273,
1758,
12,
20,
1769,
203,
203,
3639,
3626,
1166,
13621,
12,
1673,
13621,
16,
341,
304,
42,
4610,
13621,
1769,
203,
3639,
3626,
1166,
8579,
13621,
12,
1673,
8579,
13621,
16,
4634,
59,
304,
42,
4610,
13621,
1769,
203,
203,
3639,
327,
2254,
12,
668,
18,
3417,
67,
3589,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./interfaces/IERC721.sol";
import "./utils/SafeMath.sol";
// Fixed v1 update (January 2021 update):
// - Bumped to 0.7.x sol.
// - Changed 'now' to 'block.timestamp'.
// - Added in sections related to Restoration.
// - > restore() function,
// - > extracted buy() to enable once-off transfer
// - > extracted foreclosure + transferartwork to enable once-off transfer
// What changed for V2 (June 2020 update):
// - Medium Severity Fixes:
// - Added a check on buy to prevent front-running. Needs to give currentPrice when buying.
// - Removed ability for someone to block buying through revert on ETH send. Funds get sent to a pull location.
// - Added patron check on depositWei. Since anyone can send, it can be front-run, stealing a deposit by buying before deposit clears.
// - Other Minor Changes:
// - Added past foreclosureTime() if it happened in the past.
// - Moved patron modifier checks to AFTER patronage. Thus, not necessary to have steward state anymore.
// - Removed steward state. Only check on price now. If price = zero = foreclosed.
// - Removed paid mapping. Wasn't used.
// - Moved constructor to a function in case this is used with upgradeable contracts.
// - Changed currentCollected into a view function rather than tracking variable. This fixed a bug where CC would keep growing in between ownerships.
// - Kept the numerator/denominator code (for reference), but removed to save gas costs for 100% patronage rate.
// - Changes for UI:
// - Need to have additional current price when buying.
// - foreclosureTime() will now backdate if past foreclose time.
contract ArtSteward {
/*
This smart contract collects patronage from current owner through a Harberger tax model and
takes stewardship of the artwork if the patron can't pay anymore.
Harberger Tax (COST):
- Artwork is always on sale.
- You have to have a price set.
- Tax (Patronage) is paid to maintain ownership.
- Steward maints control over ERC721.
*/
using SafeMath for uint256;
uint256 public price; //in wei
IERC721 public art; // ERC721 NFT.
uint256 public totalCollected; // all patronage ever collected
/* In the event that a foreclosure happens AFTER it should have been foreclosed already,
this variable is backdated to when it should've occurred. Thus: timeHeld is accurate to actual deposit. */
uint256 public timeLastCollected; // timestamp when last collection occurred
uint256 public deposit; // funds for paying patronage
address payable public artist; // beneficiary
uint256 public artistFund; // what artist has earned and can withdraw
/*
If for whatever reason the transfer fails when being sold,
it's added to a pullFunds such that previous owner can withdraw it.
*/
mapping (address => uint256) public pullFunds; // storage area in case a sale can't send the funds towards previous owner.
mapping (address => bool) public patrons; // list of whom have owned it
mapping (address => uint256) public timeHeld; // time held by particular patron
uint256 public timeAcquired; // when it is newly bought/sold
// percentage patronage rate. eg 5% or 100%
// granular to an additionial 10 zeroes.
uint256 patronageNumerator;
uint256 patronageDenominator;
// mainnet
address public restorer;
uint256 public snapshotV1Price;
address public snapshotV1Owner;
bool public restored = false;
IERC721 public oldV1; // for checking if allowed to transfer
constructor(address payable _artist, address _artwork,
uint256 _snapshotV1Price,
address _snapshotV1Owner,
address _oldV1Address) payable {
patronageNumerator = 50000000000; // 5%
patronageDenominator = 1000000000000;
art = IERC721(_artwork);
art.setup();
artist = _artist;
// Restoration-specific setup.
oldV1 = IERC721(_oldV1Address);
restorer = msg.sender; // this must be deployed by the Restoration contract.
snapshotV1Price = _snapshotV1Price;
snapshotV1Owner = _snapshotV1Owner;
//sets up initial parameters for foreclosure
_initForecloseIfNecessary();
}
function restore() public payable {
require(restored == false, "RESTORE: Artwork already restored");
require(msg.sender == restorer, "RESTORE: Can only be restored by restoration contract");
// newPrice, oldPrice, owner
_buy(snapshotV1Price, 0, snapshotV1Owner);
restored = true;
}
event LogBuy(address indexed owner, uint256 indexed price);
event LogPriceChange(uint256 indexed newPrice);
event LogForeclosure(address indexed prevOwner);
event LogCollection(uint256 indexed collected);
modifier onlyPatron() {
require(msg.sender == art.ownerOf(42), "Not patron");
_;
}
modifier collectPatronage() {
_collectPatronage();
_;
}
/* public view functions */
/* used internally in external actions */
// how much is owed from last collection to block.timestamp.
function patronageOwed() public view returns (uint256 patronageDue) {
return price.mul(block.timestamp.sub(timeLastCollected)).mul(patronageNumerator).div(patronageDenominator).div(365 days);
// use in 100% patronage rate
//return price.mul(block.timestamp.sub(timeLastCollected)).div(365 days);
}
/* not used internally in external actions */
function patronageOwedRange(uint256 _time) public view returns (uint256 patronageDue) {
return price.mul(_time).mul(patronageNumerator).div(patronageDenominator).div(365 days);
// used in 100% patronage rate
// return price.mul(_time).div(365 days);
}
function currentCollected() public view returns (uint256 patronageDue) {
if(timeLastCollected > timeAcquired) {
return patronageOwedRange(timeLastCollected.sub(timeAcquired));
} else { return 0; }
}
function patronageOwedWithTimestamp() public view returns (uint256 patronageDue, uint256 timestamp) {
return (patronageOwed(), block.timestamp);
}
function foreclosed() public view returns (bool) {
// returns whether it is in foreclosed state or not
// depending on whether deposit covers patronage due
// useful helper function when price should be zero, but contract doesn't reflect it yet.
uint256 collection = patronageOwed();
if(collection >= deposit) {
return true;
} else {
return false;
}
}
// same function as above, basically
function depositAbleToWithdraw() public view returns (uint256) {
uint256 collection = patronageOwed();
if(collection >= deposit) {
return 0;
} else {
return deposit.sub(collection);
}
}
/*
block.timestamp + deposit/patronage per second
block.timestamp + depositAbleToWithdraw/(price*nume/denom/365).
*/
function foreclosureTime() public view returns (uint256) {
// patronage per second
uint256 pps = price.mul(patronageNumerator).div(patronageDenominator).div(365 days);
uint256 daw = depositAbleToWithdraw();
if(daw > 0) {
return block.timestamp + depositAbleToWithdraw().div(pps);
} else if (pps > 0) {
// it is still active, but in foreclosure state
// it is block.timestamp or was in the past
uint256 collection = patronageOwed();
return timeLastCollected.add((block.timestamp.sub(timeLastCollected)).mul(deposit).div(collection));
} else {
// not active and actively foreclosed (price is zero)
return timeLastCollected; // it has been foreclosed or in foreclosure.
}
}
/* actions */
// determine patronage to pay
function _collectPatronage() public {
if (price != 0) { // price > 0 == active owned state
uint256 collection = patronageOwed();
if (collection >= deposit) { // foreclosure happened in the past
// up to when was it actually paid for?
// TLC + (time_elapsed)*deposit/collection
timeLastCollected = timeLastCollected.add((block.timestamp.sub(timeLastCollected)).mul(deposit).div(collection));
collection = deposit; // take what's left.
} else {
timeLastCollected = block.timestamp;
} // normal collection
deposit = deposit.sub(collection);
totalCollected = totalCollected.add(collection);
artistFund = artistFund.add(collection);
emit LogCollection(collection);
_forecloseIfNecessary();
}
}
function buy(uint256 _newPrice, uint256 _currentPrice) public payable collectPatronage {
_buy(_newPrice, _currentPrice, msg.sender);
}
// extracted out for initial setup
function _buy(uint256 _newPrice, uint256 _currentPrice, address _newOwner) internal {
/*
this is protection against a front-run attack.
the person will only buy the artwork if it is what they agreed to.
thus: someone can't buy it from under them and change the price, eating into their deposit.
*/
require(price == _currentPrice, "Current Price incorrect");
require(_newPrice > 0, "Price is zero");
require(msg.value > price, "Not enough"); // >, coz need to have at least something for deposit
address currentOwner = art.ownerOf(42);
uint256 totalToPayBack = price.add(deposit);
if(totalToPayBack > 0) { // this won't execute if steward owns it. price = 0. deposit = 0.
// pay previous owner their price + deposit back.
address payable payableCurrentOwner = address(uint160(currentOwner));
bool transferSuccess = payableCurrentOwner.send(totalToPayBack);
// if the send fails, keep the funds separate for the owner
if(!transferSuccess) { pullFunds[currentOwner] = pullFunds[currentOwner].add(totalToPayBack); }
}
// new purchase
timeLastCollected = block.timestamp;
deposit = msg.value.sub(price);
transferArtworkTo(currentOwner, _newOwner, _newPrice);
emit LogBuy(_newOwner, _newPrice);
}
/* Only Patron Actions */
function depositWei() public payable collectPatronage onlyPatron {
deposit = deposit.add(msg.value);
}
function changePrice(uint256 _newPrice) public collectPatronage onlyPatron {
require(_newPrice > 0, 'Price is zero');
price = _newPrice;
emit LogPriceChange(price);
}
function withdrawDeposit(uint256 _wei) public collectPatronage onlyPatron {
_withdrawDeposit(_wei);
}
function exit() public collectPatronage onlyPatron {
_withdrawDeposit(deposit);
}
/* Actions that don't affect state of the artwork */
/* Artist Actions */
function withdrawArtistFunds() public {
require(msg.sender == artist, "Not artist");
uint256 toSend = artistFund;
artistFund = 0;
artist.transfer(toSend);
}
/* Withdrawing Stuck Deposits */
/* To reduce complexity, pull funds are entirely separate from current deposit */
function withdrawPullFunds() public {
require(pullFunds[msg.sender] > 0, "No pull funds available.");
uint256 toSend = pullFunds[msg.sender];
pullFunds[msg.sender] = 0;
msg.sender.transfer(toSend);
}
/* internal */
function _withdrawDeposit(uint256 _wei) internal {
// note: can withdraw whole deposit, which puts it in immediate to be foreclosed state.
require(deposit >= _wei, 'Withdrawing too much');
deposit = deposit.sub(_wei);
msg.sender.transfer(_wei); // msg.sender == patron
_forecloseIfNecessary();
}
function _forecloseIfNecessary() internal {
if(deposit == 0) {
// become steward of artwork (aka foreclose)
address currentOwner = art.ownerOf(42);
transferArtworkTo(currentOwner, address(this), 0);
emit LogForeclosure(currentOwner);
}
}
// doesn't require v1 owner check to set up.
function _initForecloseIfNecessary() internal {
if(deposit == 0) {
// become steward of artwork (aka foreclose)
address currentOwner = art.ownerOf(42);
_transferArtworkTo(currentOwner, address(this), 0);
emit LogForeclosure(currentOwner);
}
}
function transferArtworkTo(address _currentOwner, address _newOwner, uint256 _newPrice) internal {
// a symbolic check to ensure that the old V1 is still blocked and owned by the Restorer
// (the old V1 is thus a part of the new v1)
// if this bond is broken, both artworks will seize
require(oldV1.ownerOf(42) == restorer, "RESTORE: Old V1 is not owned by the Restorer");
_transferArtworkTo(_currentOwner, _newOwner, _newPrice);
}
function _transferArtworkTo(address _currentOwner, address _newOwner, uint256 _newPrice) internal {
// note: it would also tabulate time held in stewardship by smart contract
timeHeld[_currentOwner] = timeHeld[_currentOwner].add((timeLastCollected.sub(timeAcquired)));
art.transferFrom(_currentOwner, _newOwner, 42);
price = _newPrice;
timeAcquired = block.timestamp;
patrons[_newOwner] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./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;
function setup() external;
}
// 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.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);
} | this won't execute if steward owns it. price = 0. deposit = 0.
| if(totalToPayBack > 0) { | 484,991 | [
1,
2211,
8462,
1404,
1836,
309,
384,
359,
1060,
29065,
518,
18,
6205,
273,
374,
18,
443,
1724,
273,
374,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
12,
4963,
774,
9148,
2711,
405,
374,
13,
288,
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
] |
pragma solidity 0.6.5;
import "buidler-deploy/solc_0.6/proxy/diamond/DiamondStorageContract.sol";
import "./DungeonDataLayout.sol";
import "./DungeonEvents.sol";
import "./PureDungeon.sol";
import "../utils/BlockHashRegister.sol";
import "../characters/Characters.sol";
import "../tokens/Elements.sol";
import "../tokens/Gears.sol";
import "../player/Player.sol";
abstract contract DungeonFacetBase is DungeonDataLayout, DungeonEvents, DiamondStorageContract {
uint256 internal constant MAX_GEARS = 10;
modifier onlyOwner() {
DiamondStorage storage ds = diamondStorage();
require(msg.sender == ds.contractOwner, "Only owner is allowed to perform this action");
_;
}
modifier onlyAdmin() {
require(msg.sender == _adminContract, "NOT_AUTHORIZED_ADMIN");
_;
}
modifier onlyPlayer() {
require(msg.sender == address(_playerContract), "only players allowed");
_;
}
function _actualiseRoom(uint256 location) internal {
Room storage room = _rooms[location];
require(room.blockNumber > 0, "room not created yet");
if (room.kind == 0) {
bytes32 blockHash = _blockHashRegister.get(room.blockNumber);
if (blockHash == 0) {
// skip as block is not actualised or not in register
return;
}
_actualiseArea(location, blockHash);
(uint8 exits, uint8 kind, uint8 area_discovered) = PureDungeon._generateRoom(
location,
blockHash,
room.direction,
room.areaAtDiscovery,
room.lastRoomIndex,
room.index
);
room.exits = exits;
room.kind = kind;
uint256 areaLoc = PureDungeon._getAreaLoc(location);
Area storage area = _areas[areaLoc];
if (area.discovered != area_discovered) {
area.discovered = area_discovered;
}
emit RoomActualised(location, blockHash, exits, kind);
uint8 areaType = _areas[areaLoc].areaType;
if (room.discoverer != 0) {
CharacterData memory characterData = _getCharacterData(room.discoverer);
(uint256 numGold, uint256 numElements) = PureDungeon._computeRoomDiscoveryReward(
location,
blockHash,
characterData.class
);
if (areaType <= 5) {
_elementsContract.mint(room.discoverer, areaType, numElements);
}
_elementsContract.mint(room.discoverer, 6, numGold);
}
}
_actualiseRandomEvent(PureDungeon._getAreaLoc(location)); // room actualisation take precedence // monster
}
function _actualiseArea(uint256 location, bytes32 blockHash) internal {
uint256 areaLoc = PureDungeon._getAreaLoc(location);
uint8 areaType = _areas[areaLoc].areaType;
if (areaType == 0) {
uint64 currentNumAreas = _areaCounter.numAreas;
areaType = PureDungeon._generateArea(areaLoc, blockHash, currentNumAreas);
_areas[areaLoc].areaType = areaType;
if (areaType != 6) {
uint64 period = uint64(block.timestamp / 23 hours);
if (_areaCounter.lastPeriod != period) {
_areaCounter.lastPeriod = period;
_areaCounter.numAreas = 1;
} else {
_areaCounter.numAreas = currentNumAreas + 1;
}
}
}
}
struct CharacterData {
uint8 class;
uint16 level;
uint32 xp;
uint16 maxHP;
uint16 hp;
}
function _setCharacterData(uint256 characterId, CharacterData memory characterData) internal {
uint256 data = ((uint256(characterData.class) << 248) +
(uint256(characterData.level) << 232) +
(uint256(characterData.xp) << 200) +
(uint256(characterData.maxHP) << 184) +
(uint256(characterData.hp) << 168));
_charactersContract.setData(characterId, data);
}
function _getCharacterData(uint256 characterId) internal view returns (CharacterData memory) {
uint256 data = _charactersContract.getData(characterId);
(uint16 level, uint16 hp, uint16 maxHP, uint32 xp, uint8 class) = PureDungeon._decodeCharacterData(data);
return CharacterData(class, level, xp, maxHP, hp);
}
function _actualiseRandomEvent(uint256 areaLoc) internal {
Area storage area = _areas[areaLoc];
uint64 blockNumber = area.eventBlockNumber;
if (blockNumber != 0) {
bytes32 blockHash = _blockHashRegister.get(blockNumber);
if (blockHash == 0) {
// skip as block is not actualised or not in register
return;
}
(uint256 roomLocation, uint64 randomEvent) = PureDungeon._generateRandomEvent(areaLoc, blockHash);
uint256 monsterIndex = _checkMonsterBlockNumber(roomLocation);
Room storage room = _rooms[roomLocation];
if (room.randomEvent != 2
&& room.numActiveCharacters == 0
&& monsterIndex == 0
&& room.kind != 0
) {
room.randomEvent = randomEvent;
}
area.eventBlockNumber = 0;
}
}
/// @dev to be valid it require the room to be actualised first
function _checkMonster(uint256 location) internal view returns (uint256) {
uint256 monsterIndex = _checkMonsterBlockNumber(location);
// if (monsterIndex == 0) {
// if (_roomEvents[location] == 1) { //TODO monster indicator
// return 1;
// }
// return 0;
// }
return monsterIndex;
}
function _checkMonsterBlockNumber(uint256 location) internal view returns (uint256) {
uint64 monsterBlockNumber = _rooms[location].monsterBlockNumber;
if (monsterBlockNumber == 0) {
// no monsters
return 0;
}
bytes32 monsterBlockHash = _blockHashRegister.get(monsterBlockNumber);
if (monsterBlockHash == 0) {
// skip as monster block is not actualised
return 0;
}
bool newlyDiscoveredRoom = monsterBlockNumber == _rooms[location].blockNumber;
return
PureDungeon._generateMonsterIndex(
location,
monsterBlockHash,
1,
newlyDiscoveredRoom,
_rooms[location].kind
);
}
struct GearData {
uint16 level;
uint8 slot;
uint8 classBits; // bit array of allowed classes indexed by lsb
uint16 durability;
uint16 maxDurability; // gear is unbreakable when maxDurablity is 0
uint32 template;
}
function _setGearData(uint256 gearId, GearData memory gear) internal {
uint256 data = PureDungeon._encodeGearData(
gear.level,
gear.slot,
gear.classBits,
gear.durability,
gear.maxDurability,
gear.template
);
_gearsContract.setData(gearId, data);
}
function _getGearData(uint256 gearId) internal view returns (GearData memory) {
uint256 data = _gearsContract.getData(gearId);
(
uint16 level,
uint8 slot,
uint8 classBits,
uint16 durability,
uint16 maxDurability,
uint32 template
) = PureDungeon._decodeGearData(data);
return GearData(level, slot, classBits, durability, maxDurability, template);
}
function _addInitialGears(uint256 characterId) internal {
uint256 attackGearData = PureDungeon._encodeGearData(0, 0, 15, 10, 10, 1);
uint256 defenseGearData = PureDungeon._encodeGearData(0, 1, 15, 10, 10, 4);
uint256 attackGear = _gearsContract.mint(characterId, attackGearData);
_equip(characterId, 0, 0, attackGear, 0);
uint256 defenseGear = _gearsContract.mint(characterId, defenseGearData);
_equip(characterId, 0, 0, defenseGear, 1);
}
// TODO restrict transfer of equiped items
function _equip(
uint256 characterId,
uint16 level,
uint8 class,
uint256 id,
uint8 slot
) internal {
GearData memory gear = _getGearData(id);
require(gear.level <= level, "gear Level too high");
require((gear.classBits >> class) & 1 != 0, "invalid class");
if (slot == 0) {
require(gear.slot == 0, "only attack gear on slot 0");
_characters[characterId].slot_1 = id;
} else if (slot == 1) {
require(gear.slot == 1, "only defense gear on slot 1");
_characters[characterId].slot_2 = id;
} else if (slot == 2) {
require(gear.slot == 2, "only accessories on slot 2");
_characters[characterId].slot_3 = id;
} else if (slot == 3) {
require(gear.slot == 2, "only accessories on slot 3");
_characters[characterId].slot_4 = id;
} else if (slot == 4) {
require(gear.slot == 2, "only accessories on slot 4");
_characters[characterId].slot_5 = id;
}
emit Equip(characterId, id, gear.slot);
}
function _handleKey(
uint256 characterId,
uint256 location,
uint256 location2
) internal {
uint256 location1 = location;
if (location1 > location2) {
location1 = location2;
location2 = location;
}
if (!_isUnlocked(characterId, location1, location2)) {
require(_elementsContract.subBalanceOf(characterId, PureDungeon.KEYS) > 0, "no key");
_elementsContract.subBurnFrom(characterId, PureDungeon.KEYS, 1);
_unlockedExits[characterId][location1][location2] = true;
}
}
function _isUnlocked(
uint256 characterId,
uint256 location1,
uint256 location2
) internal view returns (bool) {
return _unlockedExits[characterId][location1][location2];
}
function _getAreaTypeForRoom(uint256 location) internal view returns (uint8) {
return _areas[PureDungeon._getAreaLoc(location)].areaType;
}
function _moveTo(
uint256 characterId,
uint256 oldLocation,
uint8 direction
) internal returns (uint256) {
(int64 x, int64 y, int64 z, ) = PureDungeon._coordinates(oldLocation);
if (PureDungeon.NORTH == direction) {
y--;
} else if (PureDungeon.EAST == direction) {
x++;
} else if (PureDungeon.SOUTH == direction) {
y++;
} else if (PureDungeon.WEST == direction) {
x--;
} else {
revert("impossible direction");
}
uint256 newLocation = PureDungeon._location(x, y, z);
Room storage currentRoom = _rooms[oldLocation];
Room storage nextRoom = _rooms[newLocation];
uint64 cb = currentRoom.blockNumber;
uint64 nb = nextRoom.blockNumber;
uint8 exitMask = uint8(2)**direction;
uint8 opositeExitMask = uint8(2)**((direction + 2) % 4);
if (cb < nb || nb == 0) {
if ((currentRoom.exits & exitMask) == exitMask) {
if ((currentRoom.exits / 2**4) & exitMask == exitMask) {
_handleKey(characterId, oldLocation, newLocation);
}
return newLocation;
}
} else if (cb > nb) {
if ((nextRoom.exits & opositeExitMask) == opositeExitMask) {
if ((nextRoom.exits / 2**4) & opositeExitMask == opositeExitMask) {
_handleKey(characterId, oldLocation, newLocation);
}
return newLocation;
}
} else {
if ((currentRoom.exits & exitMask) == exitMask || (nextRoom.exits & opositeExitMask) == opositeExitMask) {
if (oldLocation > newLocation) {
if ((nextRoom.exits / 2**4) & opositeExitMask == opositeExitMask) {
_handleKey(characterId, oldLocation, newLocation);
}
} else {
if ((currentRoom.exits / 2**4) & exitMask == exitMask) {
_handleKey(characterId, oldLocation, newLocation);
}
}
return newLocation;
}
}
revert("cant move this way");
}
function _move(
uint256 characterId,
uint256 location,
uint8 direction
) internal {
Character storage character = _characters[characterId];
Room storage currentRoom = _rooms[character.location];
Room storage nextRoom = _rooms[location];
uint64 blockNumber;
if (nextRoom.blockNumber == 0) {
_discoverRoom(location, characterId, direction);
} else {
// TODO should we actualiseRoom first, before monster ?
// TODO can we remove num active characters check?
if (
nextRoom.monsterBlockNumber == 0
&& nextRoom.numActiveCharacters == 0
&& nextRoom.randomEvent != 2
&& _roomsContract.getData(location) == 0
) {
blockNumber = uint64(block.number);
_blockHashRegister.request();
if (nextRoom.monsterBlockNumber == 0) {
nextRoom.monsterBlockNumber = blockNumber;
}
}
_actualiseRoom(location);
address benefactor = _roomBenefactor(location);
if (benefactor != address(0) && uint256(benefactor) != _charactersContract.getSubOwner(characterId)) {
_elementsContract.mintVault(benefactor, PureDungeon.FRAGMENTS, 1);
emit RoomIncome(location, benefactor, PureDungeon.FRAGMENTS, 1);
}
}
uint256 areaLoc = PureDungeon._getAreaLoc(location);
Area storage area = _areas[areaLoc];
if (area.eventBlockNumber == 0 && block.number % 3 == 0) {
if (blockNumber == 0) {
blockNumber = uint64(block.number);
_blockHashRegister.request();
}
area.eventBlockNumber = blockNumber;
emit RandomEvent(areaLoc, blockNumber);
}
currentRoom.numActiveCharacters--;
nextRoom.numActiveCharacters++;
character.location = location;
character.direction = direction;
_increaseHPXP(characterId);
}
function _increaseHPXP(uint256 characterId) internal {
CharacterData memory characterData = _getCharacterData(characterId);
if (characterData.hp < characterData.maxHP) {
characterData.hp += 1;
_setCharacterData(characterId, characterData);
}
}
function _isRoomActive(uint256 location) internal view returns (bool) {
address owner = _roomsContract.ownerOf(location);
return owner == address(this);
}
function _roomBenefactor(uint256 location) internal view returns (address){
if (_isRoomActive(location)) {
return address(_roomsContract.subOwnerOf(location));
} else {
return address(0);
}
}
function _pay(uint256 characterId, uint256 location, uint256 id, uint256 amount) internal {
address benefactor = _roomBenefactor(location);
if (benefactor != address(0)) {
uint256 share = amount / 5;
if (share > 0) {
_elementsContract.subTransferFrom(characterId, 0, id, share);
_elementsContract.transferFrom(address(this), benefactor, id, share);
emit RoomIncome(location, benefactor, id, share);
}
_elementsContract.subBurnFrom(characterId, id, amount - share);
} else {
_elementsContract.subBurnFrom(characterId, id, amount);
}
}
function _discoverRoom(
uint256 location,
uint256 discoverer,
uint8 direction
) internal {
Area storage area = _areas[PureDungeon._getAreaLoc(location)];
if (area.lastRoom > 0) {
// area is also actualised with room when necessary
_actualiseRoom(area.lastRoom);
area.lastRoomIndex = area.currentIndex;
area.lastRoom = 0;
}
_elementsContract.subBurnFrom(discoverer, PureDungeon.FRAGMENTS, PureDungeon._discoveryCost(location));
Room storage nextRoom = _rooms[location];
nextRoom.blockNumber = uint64(block.number);
nextRoom.monsterBlockNumber = uint64(block.number);
nextRoom.direction = direction;
nextRoom.areaAtDiscovery = area.discovered;
nextRoom.index = area.currentIndex++;
nextRoom.lastRoomIndex = area.lastRoomIndex;
nextRoom.discoverer = discoverer;
area.lastRoom = location;
_blockHashRegister.request();
uint256 discovererOwner = _charactersContract.getSubOwner(discoverer);
_initializeTaxDueDate(discovererOwner);
_roomsContract.mintId(location, discovererOwner);
emit RoomDiscovered(location, uint64(block.number), nextRoom.direction);
}
function _initializeTaxDueDate(uint256 owner) internal {
if (owner != 0 && _roomsContract.subBalanceOf(owner) == 0) {
uint256 dueDate = block.timestamp + 5 days;
_taxDueDate[address(owner)] = dueDate;
emit RoomTaxPay(address(owner), 0, dueDate);
}
}
}
| room actualisation take precedence monster
| _actualiseRandomEvent(PureDungeon._getAreaLoc(location)); | 2,574,700 | [
1,
13924,
3214,
10742,
4862,
14172,
225,
6921,
8190,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
18672,
784,
8529,
1133,
12,
13645,
40,
25561,
265,
6315,
588,
5484,
1333,
12,
3562,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
// ============ External Imports ============
import {INounsAuctionHouse} from "../external/interfaces/INounsAuctionHouse.sol";
// ============ Internal Imports ============
import {IMarketWrapper} from "./IMarketWrapper.sol";
/**
* @title NounsMarketWrapper
* @author Anna Carroll + Nounders
* @notice MarketWrapper contract implementing IMarketWrapper interface
* according to the logic of Nouns' Auction Houses
*/
contract NounsMarketWrapper is IMarketWrapper {
// ============ Public Immutables ============
INounsAuctionHouse public immutable market;
// ======== Constructor =========
constructor(address _nounsAuctionHouse) {
market = INounsAuctionHouse(_nounsAuctionHouse);
}
// ======== External Functions =========
/**
* @notice Determine whether there is an existing, active auction
* for this token. In the Nouns auction house, the current auction
* id is the token id, which increments sequentially, forever. The
* auction is considered active while the current block timestamp
* is less than the auction's end time.
* @return TRUE if the auction exists
*/
function auctionExists(uint256 auctionId)
public
view
override
returns (bool)
{
(uint256 currentAuctionId, , , uint256 endTime, , ) = market.auction();
return auctionId == currentAuctionId && block.timestamp < endTime;
}
/**
* @notice Determine whether the given auctionId and tokenId is active.
* We ignore nftContract since it is static for all nouns auctions.
* @return TRUE if the auctionId and tokenId matches the active auction
*/
function auctionIdMatchesToken(
uint256 auctionId,
address /* nftContract */,
uint256 tokenId
) public view override returns (bool) {
return auctionId == tokenId && auctionExists(auctionId);
}
/**
* @notice Calculate the minimum next bid for the active auction
* @return minimum bid amount
*/
function getMinimumBid(uint256 auctionId)
external
view
override
returns (uint256)
{
require(
auctionExists(auctionId),
"NounsMarketWrapper::getMinimumBid: Auction not active"
);
(, uint256 amount, , , address payable bidder, ) = market.auction();
if (bidder == address(0)) {
// if there are NO bids, the minimum bid is the reserve price
return market.reservePrice();
}
// if there ARE bids, the minimum bid is the current bid plus the increment buffer
uint8 minBidIncrementPercentage = market.minBidIncrementPercentage();
return amount + ((amount * minBidIncrementPercentage) / 100);
}
/**
* @notice Query the current highest bidder for this auction
* @return highest bidder
*/
function getCurrentHighestBidder(uint256 auctionId)
external
view
override
returns (address)
{
require(
auctionExists(auctionId),
"NounsMarketWrapper::getCurrentHighestBidder: Auction not active"
);
(, , , , address payable bidder, ) = market.auction();
return bidder;
}
/**
* @notice Submit bid to Market contract
*/
function bid(uint256 auctionId, uint256 bidAmount) external override {
// line 104 of Nouns Auction House, createBid() function
(bool success, bytes memory returnData) =
address(market).call{value: bidAmount}(
abi.encodeWithSignature(
"createBid(uint256)",
auctionId
)
);
require(success, string(returnData));
}
/**
* @notice Determine whether the auction has been finalized
* @return TRUE if the auction has been finalized
*/
function isFinalized(uint256 auctionId)
external
view
override
returns (bool)
{
(uint256 currentAuctionId, , , , , bool settled) = market.auction();
bool settledNormally = auctionId != currentAuctionId;
bool settledWhenPaused = auctionId == currentAuctionId && settled;
return settledNormally || settledWhenPaused;
}
/**
* @notice Finalize the results of the auction
*/
function finalize(uint256 /* auctionId */) external override {
if (market.paused()) {
market.settleAuction();
} else {
market.settleCurrentAndCreateNewAuction();
}
}
}
// SPDX-License-Identifier: GPL-3.0
/// @title Interface for Noun Auction Houses
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.5;
interface INounsAuctionHouse {
struct Auction {
// ID for the Noun (ERC721 token ID)
uint256 nounId;
// The current highest bid amount
uint256 amount;
// The time that the auction started
uint256 startTime;
// The time that the auction is scheduled to end
uint256 endTime;
// The address of the current highest bid
address payable bidder;
// Whether or not the auction has been settled
bool settled;
}
event AuctionCreated(uint256 indexed nounId, uint256 startTime, uint256 endTime);
event AuctionBid(uint256 indexed nounId, address sender, uint256 value, bool extended);
event AuctionExtended(uint256 indexed nounId, uint256 endTime);
event AuctionSettled(uint256 indexed nounId, address winner, uint256 amount);
event AuctionTimeBufferUpdated(uint256 timeBuffer);
event AuctionReservePriceUpdated(uint256 reservePrice);
event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage);
function reservePrice() external view returns (uint256);
function minBidIncrementPercentage() external view returns (uint8);
function auction() external view returns (uint256, uint256, uint256, uint256, address payable, bool);
function settleAuction() external;
function settleCurrentAndCreateNewAuction() external;
function createBid(uint256 nounId) external payable;
function pause() external;
function unpause() external;
function paused() external view returns (bool);
function setTimeBuffer(uint256 timeBuffer) external;
function setReservePrice(uint256 reservePrice) external;
function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/**
* @title IMarketWrapper
* @author Anna Carroll
* @notice IMarketWrapper provides a common interface for
* interacting with NFT auction markets.
* Contracts can abstract their interactions with
* different NFT markets using IMarketWrapper.
* NFT markets can become compatible with any contract
* using IMarketWrapper by deploying a MarketWrapper contract
* that implements this interface using the logic of their Market.
*
* WARNING: MarketWrapper contracts should NEVER write to storage!
* When implementing a MarketWrapper, exercise caution; a poorly implemented
* MarketWrapper contract could permanently lose access to the NFT or user funds.
*/
interface IMarketWrapper {
/**
* @notice Determine whether there is an existing auction
* for this token on the underlying market
* @return TRUE if the auction exists
*/
function auctionExists(uint256 auctionId) external view returns (bool);
/**
* @notice Determine whether the given auctionId is
* an auction for the tokenId + nftContract
* @return TRUE if the auctionId matches the tokenId + nftContract
*/
function auctionIdMatchesToken(
uint256 auctionId,
address nftContract,
uint256 tokenId
) external view returns (bool);
/**
* @notice Calculate the minimum next bid for this auction
* @return minimum bid amount
*/
function getMinimumBid(uint256 auctionId) external view returns (uint256);
/**
* @notice Query the current highest bidder for this auction
* @return highest bidder
*/
function getCurrentHighestBidder(uint256 auctionId)
external
view
returns (address);
/**
* @notice Submit bid to Market contract
*/
function bid(uint256 auctionId, uint256 bidAmount) external;
/**
* @notice Determine whether the auction has been finalized
* @return TRUE if the auction has been finalized
*/
function isFinalized(uint256 auctionId) external view returns (bool);
/**
* @notice Finalize the results of the auction
*/
function finalize(uint256 auctionId) external;
}
| * @notice Determine whether there is an existing, active auction for this token. In the Nouns auction house, the current auction id is the token id, which increments sequentially, forever. The auction is considered active while the current block timestamp is less than the auction's end time. @return TRUE if the auction exists/ | function auctionExists(uint256 auctionId)
public
view
override
returns (bool)
{
(uint256 currentAuctionId, , , uint256 endTime, , ) = market.auction();
return auctionId == currentAuctionId && block.timestamp < endTime;
}
| 13,835,615 | [
1,
8519,
2856,
1915,
353,
392,
2062,
16,
2695,
279,
4062,
364,
333,
1147,
18,
657,
326,
423,
465,
87,
279,
4062,
23867,
16,
326,
783,
279,
4062,
612,
353,
326,
1147,
612,
16,
1492,
17071,
695,
6979,
6261,
16,
21238,
18,
1021,
279,
4062,
353,
7399,
2695,
1323,
326,
783,
1203,
2858,
353,
5242,
2353,
326,
279,
4062,
1807,
679,
813,
18,
327,
5383,
309,
326,
279,
4062,
1704,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
279,
4062,
4002,
12,
11890,
5034,
279,
4062,
548,
13,
203,
1377,
1071,
203,
1377,
1476,
203,
1377,
3849,
203,
1377,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
261,
11890,
5034,
783,
37,
4062,
548,
16,
269,
269,
2254,
5034,
13859,
16,
269,
262,
273,
13667,
18,
69,
4062,
5621,
203,
3639,
327,
279,
4062,
548,
422,
783,
37,
4062,
548,
597,
1203,
18,
5508,
411,
13859,
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
] |
./partial_match/4/0xacfD1f6002938B156Aa186827985742Da4FA0ca2/sources/Rookie_v6.sol | Rewards added to staking contract | totalReward = totalReward.add(rewardAmount);
| 8,517,761 | [
1,
17631,
14727,
3096,
358,
384,
6159,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2078,
17631,
1060,
273,
2078,
17631,
1060,
18,
1289,
12,
266,
2913,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x19D59Ea6A136Cc5Fd55e09b2Bacc745B2a0B4eE8/sources/contracts/interfaces/ICommunity.sol | unix timestamp when repayment starts
| uint256 repaymentStartDate; | 671,258 | [
1,
21136,
2858,
1347,
2071,
2955,
2542,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
2071,
2955,
22635,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IMerkleDistributor.sol";
import "./merkle/MerkleProof.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
contract MerkleDistributor is IMerkleDistributor, Initializable, OwnableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
address public override token;
bytes32 public override merkleRoot;
uint256 public expiry;
address public constant CURVE_BTC_ADDRESS = 0xDe79d36aB6D2489dd36729A657a25f299Cb2Fbca;
// This is a packed array of booleans.
mapping(uint256 => uint256) private claimedBitMap;
function initialize(address token_, bytes32 merkleRoot_, uint256 expiry_) public initializer {
require(token_ != address(0x0), "token not set");
require(merkleRoot_ != bytes32(0x0), "merkleRoot not set");
require(expiry_ != uint256(0x0), "expiry not set");
__Ownable_init();
token = token_;
merkleRoot = merkleRoot_;
expiry = expiry_;
}
function isClaimed(uint256 index) public view override returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override {
require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.');
require(block.timestamp < expiry, "Claim expired.");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
require(IERC20Upgradeable(CURVE_BTC_ADDRESS).balanceOf(account) >= 10 ** 18, "Must have CurveBTC+");
// Mark it claimed and send the token.
_setClaimed(index);
IERC20Upgradeable(token).safeTransfer(account, amount);
emit Claimed(index, account, amount, expiry);
}
function withdraw(address account, uint256 amount) external onlyOwner {
//require(block.timestamp > expiry, "not expired");
IERC20Upgradeable(token).safeTransfer(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Allows anyone to claim a token if they exist in a merkle root.
interface IMerkleDistributor {
// Returns the address of the token distributed by this contract.
function token() external view returns (address);
// Returns the merkle root of the merkle tree containing account balances available to claim.
function merkleRoot() external view returns (bytes32);
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(uint256 index, address account, uint256 amount, uint256 expiry);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| Allows anyone to claim a token if they exist in a merkle root. Returns the address of the token distributed by this contract. Returns the merkle root of the merkle tree containing account balances available to claim. Returns true if the index has been marked claimed. Claim the given amount of the token to the given address. Reverts if the inputs are invalid. This event is triggered whenever a call to #claim succeeds. | interface IMerkleDistributor {
function token() external view returns (address);
function merkleRoot() external view returns (bytes32);
function isClaimed(uint256 index) external view returns (bool);
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
event Claimed(uint256 index, address account, uint256 amount, uint256 expiry);
pragma solidity ^0.8.0;
}
| 1,478,931 | [
1,
19132,
1281,
476,
358,
7516,
279,
1147,
309,
2898,
1005,
316,
279,
30235,
1365,
18,
2860,
326,
1758,
434,
326,
1147,
16859,
635,
333,
6835,
18,
2860,
326,
30235,
1365,
434,
326,
30235,
2151,
4191,
2236,
324,
26488,
2319,
358,
7516,
18,
2860,
638,
309,
326,
770,
711,
2118,
9350,
7516,
329,
18,
18381,
326,
864,
3844,
434,
326,
1147,
358,
326,
864,
1758,
18,
868,
31537,
309,
326,
4540,
854,
2057,
18,
1220,
871,
353,
10861,
17334,
279,
745,
358,
7516,
21933,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
5831,
6246,
264,
15609,
1669,
19293,
288,
203,
565,
445,
1147,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
565,
445,
30235,
2375,
1435,
3903,
1476,
1135,
261,
3890,
1578,
1769,
203,
565,
445,
353,
9762,
329,
12,
11890,
5034,
770,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
565,
445,
7516,
12,
11890,
5034,
770,
16,
1758,
2236,
16,
2254,
5034,
3844,
16,
1731,
1578,
8526,
745,
892,
30235,
20439,
13,
3903,
31,
203,
203,
565,
871,
18381,
329,
12,
11890,
5034,
770,
16,
1758,
2236,
16,
2254,
5034,
3844,
16,
2254,
5034,
10839,
1769,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x13fc6acaDAd9a3F22f68912ec843570183fCd2A7/sources/MCPToken.sol | tokens vest according to the division percentage and claim frequency. Can't claim funds until claim frequency is reached | contract ERC20Vestable is ERC20 {
mapping(address => uint256) public _vestingAllowances;
mapping(address => uint256) public _claimFrequency;
mapping(address => uint256) public _claimAmounts;
mapping(address => uint256) public _lastClaimed;
function _grantFunds(address beneficiary) internal {
require(
_vestingAllowances[beneficiary] > 0 &&
_vestingAllowances[beneficiary] >= _claimAmounts[beneficiary],
"Entire allowance already claimed, or no initial aloowance"
);
_vestingAllowances[beneficiary] = _vestingAllowances[beneficiary].sub(
_claimAmounts[beneficiary]
);
_mint(
beneficiary,
_claimAmounts[beneficiary].mul(10**uint256(18))
);
}
function _addBeneficiary(address beneficiary, uint256 amount, uint8 divide, uint256 claimFrequency)
internal
{
_vestingAllowances[beneficiary] = amount;
_claimFrequency[beneficiary] = claimFrequency;
_claimAmounts[beneficiary] = amount.div(divide);
_lastClaimed[beneficiary] = now;
_grantFunds(beneficiary);
}
function claimFunds() public {
require(
_lastClaimed[msg.sender] != 0 &&
now >= _lastClaimed[msg.sender].add(_claimFrequency[msg.sender]),
"Allowance cannot be claimed more than once in a cycle. Please check last claimed time."
);
_lastClaimed[msg.sender] = now;
_grantFunds(msg.sender);
}
}
| 4,039,696 | [
1,
7860,
331,
395,
4888,
358,
326,
16536,
11622,
471,
7516,
8670,
18,
4480,
1404,
7516,
284,
19156,
3180,
7516,
8670,
353,
8675,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
6835,
4232,
39,
3462,
58,
395,
429,
353,
4232,
39,
3462,
288,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
90,
10100,
7009,
6872,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
14784,
13865,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
14784,
6275,
87,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
2722,
9762,
329,
31,
203,
203,
203,
565,
445,
389,
16243,
42,
19156,
12,
2867,
27641,
74,
14463,
814,
13,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
389,
90,
10100,
7009,
6872,
63,
70,
4009,
74,
14463,
814,
65,
405,
374,
597,
203,
7734,
389,
90,
10100,
7009,
6872,
63,
70,
4009,
74,
14463,
814,
65,
1545,
389,
14784,
6275,
87,
63,
70,
4009,
74,
14463,
814,
6487,
203,
5411,
315,
14199,
577,
1699,
1359,
1818,
7516,
329,
16,
578,
1158,
2172,
279,
383,
543,
1359,
6,
203,
3639,
11272,
203,
3639,
389,
90,
10100,
7009,
6872,
63,
70,
4009,
74,
14463,
814,
65,
273,
389,
90,
10100,
7009,
6872,
63,
70,
4009,
74,
14463,
814,
8009,
1717,
12,
203,
5411,
389,
14784,
6275,
87,
63,
70,
4009,
74,
14463,
814,
65,
203,
3639,
11272,
203,
3639,
389,
81,
474,
12,
203,
5411,
27641,
74,
14463,
814,
16,
203,
5411,
389,
14784,
6275,
87,
63,
70,
4009,
74,
14463,
814,
8009,
16411,
12,
2163,
636,
11890,
5034,
12,
2643,
3719,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
389,
1289,
38,
4009,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @notice Transition guard functions
*
* - Machine: StopWatch
* - Guards: Paused/Enter, Ready/Enter
*/
contract StopWatchGuards {
// Events
event StopWatchReset(address indexed user);
event StopWatchRunning(address indexed user, uint256 elapsed);
event StopWatchPaused(address indexed user, uint256 elapsed);
// States
string private constant READY = "Ready";
string private constant RUNNING = "Running";
string private constant PAUSED = "Paused";
// Machine-specific storage slot
bytes32 private constant STOPWATCH_SLOT = keccak256("fismo.example.stopwatch.storage.slot");
/// User-specific slice of the stopwatch memory bank, accessed by state guards
struct UserSlice {
// starting block.timestamp
uint256 timeStarted;
// elapsed time
uint256 timeElapsed;
// block.timestamp when last paused
uint256 timeLastPaused;
// total time spent in paused state
uint256 totalTimePaused;
}
/**
* Storage slot structure
*/
struct StopWatchSlot {
// maps user wallet => UserSlice struct
mapping(address => UserSlice) memoryBank;
}
/**
* @notice Get the StopWatch machine's storage slot
*
* @return stopWatchStorage - StopWatch storage slot
*/
function stopWatchSlot()
internal
pure
returns (StopWatchSlot storage stopWatchStorage)
{
bytes32 position = STOPWATCH_SLOT;
assembly {
stopWatchStorage.slot := position
}
}
/**
* @notice Get the user's slice of the memory bank
*
* @param _user - the wallet address of the user
* @return slice - the user's slice of the memory bank as a UserSlice struct
*/
function userSlice(address _user)
internal
view
returns (UserSlice storage slice)
{
slice = stopWatchSlot().memoryBank[_user];
}
/**
* @notice Compare two strings
*/
function compare(string memory _a, string memory _b)
internal
pure
returns
(bool)
{
return keccak256(abi.encodePacked(_a)) == keccak256(abi.encodePacked(_b));
}
/**
* @notice Calculate / store time elapsed for user
*/
function calcTimeElapsed(UserSlice memory slice)
internal
view
{
slice.timeElapsed = block.timestamp - (block.timestamp + slice.totalTimePaused);
}
// -------------------------------------------------------------------------
// TRANSITION GUARDS
// -------------------------------------------------------------------------
// Ready / Enter
// Initial state.
// Valid prior states: Paused
// - resets user memory
// - emits StopWatchReset if previously paused
function StopWatch_Ready_Enter(address _user, string memory _priorStateName)
external
returns(string memory message)
{
// Reset user memory
delete stopWatchSlot().memoryBank[_user];
// If previous state was paused, emit reset event
if (compare(_priorStateName, PAUSED)) emit StopWatchReset(_user);
// Respond with new state
message = READY;
}
// Ready / Exit
// Valid next states: Running
// - Stores start time
function StopWatch_Ready_Exit(address _user, string memory _nextStateName)
external
returns(string memory message)
{
stopWatchSlot().memoryBank[_user].timeStarted = block.timestamp;
}
// Running / Enter
// Valid prior states: Ready, Paused
// - emits StopWatchRunning if previously paused
function StopWatch_Running_Enter(address _user, string memory _priorStateName)
external
returns(string memory message)
{
emit StopWatchRunning(_user, userSlice(_user).timeElapsed);
message = RUNNING;
}
// Paused / Enter
// Valid prior states: Running
// - stores time last paused
// - calculates & stores time elapsed
// - emits StopWatchPaused event
function StopWatch_Paused_Enter(address _user, string memory _priorStateName)
external
returns(string memory message)
{
UserSlice storage slice = userSlice(_user);
slice.timeLastPaused = block.timestamp;
calcTimeElapsed(slice);
emit StopWatchPaused(_user, block.timestamp);
message = PAUSED;
}
// Paused / Exit
// Valid next states: Running
// - calculates & stores total time paused
// - calculates and stores time elapsed
function StopWatch_Paused_Exit(address _user, string memory _priorStateName)
external
returns(string memory message)
{
UserSlice storage slice = userSlice(_user);
slice.totalTimePaused = slice.totalTimePaused + (block.timestamp - slice.timeLastPaused);
calcTimeElapsed(slice);
}
} | Paused / Enter Valid prior states: Running - stores time last paused - calculates & stores time elapsed - emits StopWatchPaused event | function StopWatch_Paused_Enter(address _user, string memory _priorStateName)
external
returns(string memory message)
{
UserSlice storage slice = userSlice(_user);
slice.timeLastPaused = block.timestamp;
calcTimeElapsed(slice);
emit StopWatchPaused(_user, block.timestamp);
message = PAUSED;
}
| 12,771,596 | [
1,
28590,
342,
15439,
2364,
6432,
5493,
30,
20480,
300,
9064,
813,
1142,
17781,
300,
17264,
473,
9064,
813,
9613,
300,
24169,
5131,
5234,
28590,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5131,
5234,
67,
28590,
67,
10237,
12,
2867,
389,
1355,
16,
533,
3778,
389,
17927,
1119,
461,
13,
203,
565,
3903,
203,
565,
1135,
12,
1080,
3778,
883,
13,
203,
565,
288,
203,
3639,
2177,
5959,
2502,
2788,
273,
729,
5959,
24899,
1355,
1769,
203,
3639,
2788,
18,
957,
3024,
28590,
273,
1203,
18,
5508,
31,
203,
3639,
7029,
950,
28827,
12,
6665,
1769,
203,
3639,
3626,
5131,
5234,
28590,
24899,
1355,
16,
1203,
18,
5508,
1769,
203,
3639,
883,
273,
15662,
20093,
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
] |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
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) {
// 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;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* 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));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* 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 { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.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");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.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);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` 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 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: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
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 `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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_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());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
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));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
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;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
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.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
| Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees have been taken from this contract in the past, then the raw value will be larger than the user-readable value. | function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
| 99,449 | [
1,
5692,
279,
729,
17,
11018,
4508,
2045,
287,
460,
1368,
279,
1831,
460,
716,
9484,
364,
1818,
17,
428,
281,
730,
1656,
281,
18,
971,
1281,
1656,
281,
1240,
2118,
9830,
628,
333,
6835,
316,
326,
8854,
16,
1508,
326,
1831,
460,
903,
506,
10974,
2353,
326,
729,
17,
11018,
460,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
6283,
774,
4809,
13535,
2045,
287,
12,
7505,
2148,
18,
13290,
3778,
4508,
2045,
287,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
7505,
2148,
18,
13290,
3778,
1831,
13535,
2045,
287,
13,
203,
565,
288,
203,
3639,
327,
4508,
2045,
287,
18,
2892,
12,
71,
11276,
14667,
23365,
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
] |
/*
,▄▓▓██▌ ,╓▄▄▓▓▓▓▓▓▓▓▄▄▄,,
,▓██▓███▓▄▓███▓╬╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▄,
▄█ ▓██╬╣███████╬▓▀╬╬▓▓▓████████████▓█████▄,
▓██▌ ▓██╬╣██████╬▓▌ ██████████████████████▌╙╙▀ⁿ
▐████████╬▓████▓▓█╨ ▄ ╟█████████▓▓╬╬╬╬╬▓▓█████▓▄
└▀▓▓▄╓ ╟█▓╣█████▓██████▀ ╓█▌ ███████▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓██▓▄
└▀████▓▄╥ ▐██╬╬██████████╙ Æ▀─ ▓███▀╚╠╬╩▀▀███████▓▓╬╬╬╬╬╬╬╬╬██▄
└▀██▓▀▀█████▓╬▓██████▀ ▄█████▒╠" └╙▓██████▓╬╬╬╬╬╬╬╬██▄
└▀██▄,└╙▀▀████▌└╙ ^"▀╙╙╙"╙██ @▄ ╙▀███████╬╬╬╬╬╬╬██µ
└▀██▓▄, ██▌ ╒ ╙█▓ ]▓█▓╔ ▀███████▓╬╬╬╬╬▓█▌
▀█████ ▓ ╟█▌ ]╠██▓░▒╓ ▀████████╬╬╬╬╣█▌
▐████ ╓█▀█▌ ,██▌ ╚Å███▓▒▒╠╓ ╙█████████╬╬╬╣█▌
└████ ▓█░░▓█ ▀▀▀ φ▒╫████▒▒▒▒╠╓ █████████▓╬╬▓█µ
╘███µ ▌▄█▓▄▓▀` ,▀ ,╔╠░▓██████▌╠▒▒▒φ ██████████╬╬██
▐████µ╙▓▀` ,▀╙,╔╔φφφ╠░▄▓███████▌░▓╙▒▒▒╠ └██╬███████╬▓█⌐
╫██ ▓▌ ▌φ▒▒░▓██████████████▌▒░▓╚▒▒▒╠ ▓██╬▓██████╣█▌
██▌ ▌╔▒▒▄████████████████▒▒▒░▌╠▒▒▒≥▐██▓╬╬███████▌
██▌ ,╓φ╠▓«▒▒▓████▀ ▀█████████▌▒▒▒╟░▒▒▒▒▐███╬╬╣████▓█▌
▐██ ╠▒▄▓▓███▓████└ ▀████████▌▒▒░▌╚▒▒▒▐███▓╬╬████ ╙▌
███ ) ╠▒░░░▒░╬████▀ └████████░▒▒░╬∩▒▒▓████╬╬╣███
▓██ ╠╠▒▒▐█▀▀▌`░╫██ ███████▒▒▒▒░▒▒½█████╬╬╣███
███ ,█▄ ╠▒▒▒╫▌,▄▀,▒╫██ ╟██████▒▒▒░╣⌠▒▓█████╬╬╣██▌
╘██µ ██` ╠▒▒░██╬φ╠▄▓██` ██████░░▌φ╠░▓█████▓╬╬▓██
╟██ .φ╠▒░▄█▀░░▄██▀└ █████▌▒╣φ▒░▓██████╬╬╣██
▀██▄▄▄╓▄███████▀ ▐█████░▓φ▒▄███████▓╬╣██
╙▀▀▀██▀└ ████▓▄▀φ▄▓████████╬▓█▀
▓███╬╩╔╣██████████▓██└
╓████▀▄▓████████▀████▀
,▓███████████████─]██╙
,▄▓██████████████▀└ ╙
,╓▄▓███████████████▀╙
`"▀▀▀████████▀▀▀▀`▄███▀▀└
└└
11\ 11\ 11\ 11\ 11\ 11\ 11\
1111 | \__| 11 | 111\ 11 | 11 | 11 |
\_11 | 11\ 1111111\ 1111111\ 1111111\ 1111\ 11 | 111111\ 111111\ 11\ 11\ 11\ 111111\ 111111\ 11 | 11\
11 | 11 |11 __11\ 11 _____|11 __11\ 11 11\11 |11 __11\\_11 _| 11 | 11 | 11 |11 __11\ 11 __11\ 11 | 11 |
11 | 11 |11 | 11 |11 / 11 | 11 | 11 \1111 |11111111 | 11 | 11 | 11 | 11 |11 / 11 |11 | \__|111111 /
11 | 11 |11 | 11 |11 | 11 | 11 | 11 |\111 |11 ____| 11 |11\ 11 | 11 | 11 |11 | 11 |11 | 11 _11<
111111\ 11 |11 | 11 |\1111111\ 11 | 11 | 11 | \11 |\1111111\ \1111 |\11111\1111 |\111111 |11 | 11 | \11\
\______|\__|\__| \__| \_______|\__| \__| \__| \__| \_______| \____/ \_____\____/ \______/ \__| \__| \__|
111111\ 11\ 11\
11 __11\ 11 | \__|
11 / 11 | 111111\ 111111\ 111111\ 111111\ 111111\ 111111\ 111111\ 11\ 111111\ 1111111\
11111111 |11 __11\ 11 __11\ 11 __11\ 11 __11\ 11 __11\ \____11\\_11 _| 11 |11 __11\ 11 __11\
11 __11 |11 / 11 |11 / 11 |11 | \__|11111111 |11 / 11 | 1111111 | 11 | 11 |11 / 11 |11 | 11 |
11 | 11 |11 | 11 |11 | 11 |11 | 11 ____|11 | 11 |11 __11 | 11 |11\ 11 |11 | 11 |11 | 11 |
11 | 11 |\1111111 |\1111111 |11 | \1111111\ \1111111 |\1111111 | \1111 |11 |\111111 |11 | 11 |
\__| \__| \____11 | \____11 |\__| \_______| \____11 | \_______| \____/ \__| \______/ \__| \__|
11\ 11 |11\ 11 | 11\ 11 |
\111111 |\111111 | \111111 |
\______/ \______/ \______/
1111111\ 11\
11 __11\ 11 |
11 | 11 | 111111\ 11\ 11\ 111111\ 111111\ 111111\
1111111 |11 __11\ 11 | 11 |\_11 _| 11 __11\ 11 __11\
11 __11< 11 / 11 |11 | 11 | 11 | 11111111 |11 | \__|
11 | 11 |11 | 11 |11 | 11 | 11 |11\ 11 ____|11 |
11 | 11 |\111111 |\111111 | \1111 |\1111111\ 11 |
\__| \__| \______/ \______/ \____/ \_______|\__|
*/
// File @openzeppelin/contracts/utils/[email protected]
// 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/helpers/EthReceiver.sol
pragma solidity ^0.7.6;
/// @title Base contract with common payable logics
abstract contract EthReceiver {
receive() external payable {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender != tx.origin, "ETH deposit rejected");
}
}
// File @openzeppelin/contracts/drafts/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// File contracts/helpers/RevertReasonParser.sol
pragma solidity ^0.7.6;
/// @title Library that allows to parse unsuccessful arbitrary calls revert reasons.
/// See https://solidity.readthedocs.io/en/latest/control-structures.html#revert for details.
/// Note that we assume revert reason being abi-encoded as Error(string) so it may fail to parse reason
/// if structured reverts appear in the future.
///
/// All unsuccessful parsings get encoded as Unknown(data) string
library RevertReasonParser {
bytes4 constant private _PANIC_SELECTOR = bytes4(keccak256("Panic(uint256)"));
bytes4 constant private _ERROR_SELECTOR = bytes4(keccak256("Error(string)"));
function parse(bytes memory data, string memory prefix) internal pure returns (string memory) {
if (data.length >= 4) {
bytes4 selector;
assembly { // solhint-disable-line no-inline-assembly
selector := mload(add(data, 0x20))
}
// 68 = 4-byte selector + 32 bytes offset + 32 bytes length
if (selector == _ERROR_SELECTOR && data.length >= 68) {
uint256 offset;
bytes memory reason;
// solhint-disable no-inline-assembly
assembly {
// 36 = 32 bytes data length + 4-byte selector
offset := mload(add(data, 36))
reason := add(data, add(36, offset))
}
/*
revert reason is padded up to 32 bytes with ABI encoder: Error(string)
also sometimes there is extra 32 bytes of zeros padded in the end:
https://github.com/ethereum/solidity/issues/10170
because of that we can't check for equality and instead check
that offset + string length + extra 36 bytes is less than overall data length
*/
require(data.length >= 36 + offset + reason.length, "Invalid revert reason");
return string(abi.encodePacked(prefix, "Error(", reason, ")"));
}
// 36 = 4-byte selector + 32 bytes integer
else if (selector == _PANIC_SELECTOR && data.length == 36) {
uint256 code;
// solhint-disable no-inline-assembly
assembly {
// 36 = 32 bytes data length + 4-byte selector
code := mload(add(data, 36))
}
return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")"));
}
}
return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")"));
}
function _toHex(uint256 value) private pure returns(string memory) {
return _toHex(abi.encodePacked(value));
}
function _toHex(bytes memory data) private pure returns(string memory) {
bytes16 alphabet = 0x30313233343536373839616263646566;
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 * i + 2] = alphabet[uint8(data[i] >> 4)];
str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)];
}
return string(str);
}
}
// File contracts/interfaces/IDaiLikePermit.sol
pragma solidity ^0.7.6;
/// @title Interface for DAI-style permits
interface IDaiLikePermit {
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// File contracts/helpers/Permitable.sol
pragma solidity ^0.7.6;
/// @title Base contract with common permit handling logics
contract Permitable {
function _permit(address token, bytes calldata permit) internal {
if (permit.length > 0) {
bool success;
bytes memory result;
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
} else if (permit.length == 32 * 8) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit));
} else {
revert("Wrong permit length");
}
if (!success) {
revert(RevertReasonParser.parse(result, "Permit failed: "));
}
}
}
}
// File contracts/helpers/UniERC20.sol
pragma solidity ^0.7.6;
library UniERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(IERC20 token, address payable to, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(IERC20 token, address to, uint256 amount) internal {
require(!isETH(token), "Approve called on ETH");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(abi.encodeWithSelector(token.approve.selector, to, amount));
if (!success || (returndata.length > 0 && !abi.decode(returndata, (bool)))) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, to, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, to, amount));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = address(token).call(data);
if (!success) {
revert(RevertReasonParser.parse(result, "Low-level call failed: "));
}
if (result.length > 0) { // Return data is optional
require(abi.decode(result, (bool)), "ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/IAggregationExecutor.sol
pragma solidity ^0.7.6;
/// @title Interface for making arbitrary calls during swap
interface IAggregationExecutor {
/// @notice Make calls on `msgSender` with specified data
function callBytes(address msgSender, bytes calldata data) external payable; // 0x2636f7f8
}
// File @openzeppelin/contracts/drafts/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// File contracts/helpers/ECDSA.sol
pragma solidity ^0.7.6;
/**
* @dev Simplified copy of OpenZeppelin ECDSA library downgraded to 0.7.6
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/541e82144f691aa171c53ba8c3b32ef7f05b99a5/contracts/utils/cryptography/ECDSA.sol
*
* 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` 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) {
// 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 { // solhint-disable-line no-inline-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 { // solhint-disable-line no-inline-assembly
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return address(0);
}
}
/**
* @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) {
bytes32 s;
uint8 v;
assembly { // solhint-disable-line no-inline-assembly
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @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) {
// 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);
}
if (v != 27 && v != 28) {
return address(0);
}
// 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);
}
return signer;
}
}
// File contracts/interfaces/IERC1271.sol
pragma solidity ^0.7.6;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// File contracts/interfaces/IWETH.sol
pragma solidity ^0.7.6;
/// @title Interface for WETH tokens
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File contracts/LimitOrderProtocolRFQ.sol
pragma solidity ^0.7.6;
pragma abicoder v2;
contract LimitOrderProtocolRFQ is EthReceiver, EIP712("1inch RFQ", "2"), Permitable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event OrderFilledRFQ(
bytes32 orderHash,
uint256 makingAmount
);
struct OrderRFQ {
// lowest 64 bits is the order id, next 64 bits is the expiration timestamp
// highest bit is unwrap WETH flag which is set on taker's side
// [unwrap eth(1 bit) | unused (127 bits) | expiration timestamp(64 bits) | orderId (64 bits)]
uint256 info;
IERC20 makerAsset;
IERC20 takerAsset;
address maker;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
}
bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256(
"OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)"
);
uint256 private constant _UNWRAP_WETH_MASK = 1 << 255;
IWETH private immutable _WETH; // solhint-disable-line var-name-mixedcase
mapping(address => mapping(uint256 => uint256)) private _invalidator;
constructor(address weth) {
_WETH = IWETH(weth);
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns(bytes32) {
return _domainSeparatorV4();
}
/// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes
/// @return Result Each bit represents whenever corresponding quote was filled
function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) {
return _invalidator[maker][slot];
}
/// @notice Cancels order's quote
function cancelOrderRFQ(uint256 orderInfo) external {
_invalidateOrder(msg.sender, orderInfo);
}
/// @notice Fills order's quote, fully or partially (whichever is possible)
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
function fillOrderRFQ(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount
) external payable returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, payable(msg.sender));
}
/// @notice Fills Same as `fillOrderRFQ` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// Also allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
/// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
/// See tests for examples
function fillOrderRFQToWithPermit(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address payable target,
bytes calldata permit
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
_permit(address(order.takerAsset), permit);
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target);
}
/// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
function fillOrderRFQTo(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address payable target
) public payable returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
address maker = order.maker;
bool unwrapWETH = (order.info & _UNWRAP_WETH_MASK) > 0;
order.info = order.info & (_UNWRAP_WETH_MASK - 1); // zero-out unwrap weth flag as it is taker-only
{ // Stack too deep
uint256 info = order.info;
// Check time expiration
uint256 expiration = uint128(info) >> 64;
require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time
_invalidateOrder(maker, info);
}
{ // stack too deep
uint256 orderMakingAmount = order.makingAmount;
uint256 orderTakingAmount = order.takingAmount;
// Compute partial fill if needed
if (takingAmount == 0 && makingAmount == 0) {
// Two zeros means whole order
makingAmount = orderMakingAmount;
takingAmount = orderTakingAmount;
}
else if (takingAmount == 0) {
require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded");
takingAmount = orderTakingAmount.mul(makingAmount).add(orderMakingAmount - 1).div(orderMakingAmount);
}
else if (makingAmount == 0) {
require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded");
makingAmount = orderMakingAmount.mul(takingAmount).div(orderTakingAmount);
}
else {
revert("LOP: one of amounts should be 0");
}
}
require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount");
// Validate order
require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order");
bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order)));
_validate(maker, orderHash, signature);
// Maker => Taker
if (order.makerAsset == _WETH && unwrapWETH) {
order.makerAsset.safeTransferFrom(maker, address(this), makingAmount);
_WETH.withdraw(makingAmount);
target.transfer(makingAmount);
} else {
order.makerAsset.safeTransferFrom(maker, target, makingAmount);
}
// Taker => Maker
if (order.takerAsset == _WETH && msg.value > 0) {
require(msg.value == takingAmount, "LOP: wrong msg.value");
_WETH.deposit{ value: takingAmount }();
_WETH.transfer(maker, takingAmount);
} else {
require(msg.value == 0, "LOP: wrong msg.value");
order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount);
}
emit OrderFilledRFQ(orderHash, makingAmount);
return (makingAmount, takingAmount);
}
function _validate(address signer, bytes32 orderHash, bytes calldata signature) private view {
if (ECDSA.tryRecover(orderHash, signature) != signer) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, orderHash, signature)
);
require(success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector, "LOP: bad signature");
}
}
function _invalidateOrder(address maker, uint256 orderInfo) private {
uint256 invalidatorSlot = uint64(orderInfo) >> 8;
uint256 invalidatorBit = 1 << uint8(orderInfo);
mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker];
uint256 invalidator = invalidatorStorage[invalidatorSlot];
require(invalidator & invalidatorBit == 0, "LOP: invalidated order");
invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit;
}
}
// File contracts/UnoswapRouter.sol
pragma solidity ^0.7.6;
contract UnoswapRouter is EthReceiver, Permitable {
uint256 private constant _TRANSFER_FROM_CALL_SELECTOR_32 = 0x23b872dd00000000000000000000000000000000000000000000000000000000;
uint256 private constant _WETH_DEPOSIT_CALL_SELECTOR_32 = 0xd0e30db000000000000000000000000000000000000000000000000000000000;
uint256 private constant _WETH_WITHDRAW_CALL_SELECTOR_32 = 0x2e1a7d4d00000000000000000000000000000000000000000000000000000000;
uint256 private constant _ERC20_TRANSFER_CALL_SELECTOR_32 = 0xa9059cbb00000000000000000000000000000000000000000000000000000000;
uint256 private constant _ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
uint256 private constant _REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000;
uint256 private constant _WETH_MASK = 0x4000000000000000000000000000000000000000000000000000000000000000;
uint256 private constant _NUMERATOR_MASK = 0x0000000000000000ffffffff0000000000000000000000000000000000000000;
/// @dev WETH address is network-specific and needs to be changed before deployment.
/// It can not be moved to immutable as immutables are not supported in assembly
uint256 private constant _WETH = 0x000000000000000000000000C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 private constant _UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32 = 0x0902f1ac00000000000000000000000000000000000000000000000000000000;
uint256 private constant _UNISWAP_PAIR_SWAP_CALL_SELECTOR_32 = 0x022c0d9f00000000000000000000000000000000000000000000000000000000;
uint256 private constant _DENOMINATOR = 1000000000;
uint256 private constant _NUMERATOR_OFFSET = 160;
/// @notice Same as `unoswap` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// @param srcToken Source token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
/// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
/// See tests for examples
function unoswapWithPermit(
IERC20 srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata pools,
bytes calldata permit
) external returns(uint256 returnAmount) {
_permit(address(srcToken), permit);
return unoswap(srcToken, amount, minReturn, pools);
}
/// @notice Performs swap using Uniswap exchange. Wraps and unwraps ETH if required.
/// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
/// @param srcToken Source token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
function unoswap(
IERC20 srcToken,
uint256 amount,
uint256 minReturn,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) public payable returns(uint256 returnAmount) {
assembly { // solhint-disable-line no-inline-assembly
function reRevert() {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
function revertWithReason(m, len) {
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x20, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(0x40, m)
revert(0, len)
}
function swap(emptyPtr, swapAmount, pair, reversed, numerator, dst) -> ret {
mstore(emptyPtr, _UNISWAP_PAIR_RESERVES_CALL_SELECTOR_32)
if iszero(staticcall(gas(), pair, emptyPtr, 0x4, emptyPtr, 0x40)) {
reRevert()
}
if iszero(eq(returndatasize(), 0x60)) {
revertWithReason(0x0000001472657365727665732063616c6c206661696c65640000000000000000, 0x59) // "reserves call failed"
}
let reserve0 := mload(emptyPtr)
let reserve1 := mload(add(emptyPtr, 0x20))
if reversed {
let tmp := reserve0
reserve0 := reserve1
reserve1 := tmp
}
ret := mul(swapAmount, numerator)
ret := div(mul(ret, reserve1), add(ret, mul(reserve0, _DENOMINATOR)))
mstore(emptyPtr, _UNISWAP_PAIR_SWAP_CALL_SELECTOR_32)
switch reversed
case 0 {
mstore(add(emptyPtr, 0x04), 0)
mstore(add(emptyPtr, 0x24), ret)
}
default {
mstore(add(emptyPtr, 0x04), ret)
mstore(add(emptyPtr, 0x24), 0)
}
mstore(add(emptyPtr, 0x44), dst)
mstore(add(emptyPtr, 0x64), 0x80)
mstore(add(emptyPtr, 0x84), 0)
if iszero(call(gas(), pair, 0, emptyPtr, 0xa4, 0, 0)) {
reRevert()
}
}
let emptyPtr := mload(0x40)
mstore(0x40, add(emptyPtr, 0xc0))
let poolsOffset := add(calldataload(0x64), 0x4)
let poolsEndOffset := calldataload(poolsOffset)
poolsOffset := add(poolsOffset, 0x20)
poolsEndOffset := add(poolsOffset, mul(0x20, poolsEndOffset))
let rawPair := calldataload(poolsOffset)
switch srcToken
case 0 {
if iszero(eq(amount, callvalue())) {
revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value"
}
mstore(emptyPtr, _WETH_DEPOSIT_CALL_SELECTOR_32)
if iszero(call(gas(), _WETH, amount, emptyPtr, 0x4, 0, 0)) {
reRevert()
}
mstore(emptyPtr, _ERC20_TRANSFER_CALL_SELECTOR_32)
mstore(add(emptyPtr, 0x4), and(rawPair, _ADDRESS_MASK))
mstore(add(emptyPtr, 0x24), amount)
if iszero(call(gas(), _WETH, 0, emptyPtr, 0x44, 0, 0)) {
reRevert()
}
}
default {
if callvalue() {
revertWithReason(0x00000011696e76616c6964206d73672e76616c75650000000000000000000000, 0x55) // "invalid msg.value"
}
mstore(emptyPtr, _TRANSFER_FROM_CALL_SELECTOR_32)
mstore(add(emptyPtr, 0x4), caller())
mstore(add(emptyPtr, 0x24), and(rawPair, _ADDRESS_MASK))
mstore(add(emptyPtr, 0x44), amount)
if iszero(call(gas(), srcToken, 0, emptyPtr, 0x64, 0, 0)) {
reRevert()
}
}
returnAmount := amount
for {let i := add(poolsOffset, 0x20)} lt(i, poolsEndOffset) {i := add(i, 0x20)} {
let nextRawPair := calldataload(i)
returnAmount := swap(
emptyPtr,
returnAmount,
and(rawPair, _ADDRESS_MASK),
and(rawPair, _REVERSE_MASK),
shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
and(nextRawPair, _ADDRESS_MASK)
)
rawPair := nextRawPair
}
switch and(rawPair, _WETH_MASK)
case 0 {
returnAmount := swap(
emptyPtr,
returnAmount,
and(rawPair, _ADDRESS_MASK),
and(rawPair, _REVERSE_MASK),
shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
caller()
)
}
default {
returnAmount := swap(
emptyPtr,
returnAmount,
and(rawPair, _ADDRESS_MASK),
and(rawPair, _REVERSE_MASK),
shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
address()
)
mstore(emptyPtr, _WETH_WITHDRAW_CALL_SELECTOR_32)
mstore(add(emptyPtr, 0x04), returnAmount)
if iszero(call(gas(), _WETH, 0, emptyPtr, 0x24, 0, 0)) {
reRevert()
}
if iszero(call(gas(), caller(), returnAmount, 0, 0, 0, 0)) {
reRevert()
}
}
if lt(returnAmount, minReturn) {
revertWithReason(0x000000164d696e2072657475726e206e6f742072656163686564000000000000, 0x5a) // "Min return not reached"
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File contracts/interfaces/IUniswapV3Pool.sol
pragma solidity ^0.7.6;
interface IUniswapV3Pool {
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
}
// File contracts/interfaces/IUniswapV3SwapCallback.sol
pragma solidity ^0.7.6;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// File contracts/UnoswapV3Router.sol
pragma solidity ^0.7.6;
contract UnoswapV3Router is EthReceiver, Permitable, IUniswapV3SwapCallback {
using Address for address payable;
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 private constant _ONE_FOR_ZERO_MASK = 1 << 255;
uint256 private constant _WETH_WRAP_MASK = 1 << 254;
uint256 private constant _WETH_UNWRAP_MASK = 1 << 253;
bytes32 private constant _POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
bytes32 private constant _FF_FACTORY = 0xff1F98431c8aD98523631AE4a59f267346ea31F9840000000000000000000000;
bytes32 private constant _SELECTORS = 0x0dfe1681d21220a7ddca3f430000000000000000000000000000000000000000;
uint256 private constant _ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 private constant _MIN_SQRT_RATIO = 4295128739 + 1;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 private constant _MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342 - 1;
IWETH private immutable _WETH; // solhint-disable-line var-name-mixedcase
constructor(address weth) {
_WETH = IWETH(weth);
}
/// @notice Same as `uniswapV3SwapTo` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// @param recipient Address that will receive swap funds
/// @param srcToken Source token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
/// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
/// See tests for examples
function uniswapV3SwapToWithPermit(
address payable recipient,
IERC20 srcToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata pools,
bytes calldata permit
) external returns(uint256 returnAmount) {
_permit(address(srcToken), permit);
return uniswapV3SwapTo(recipient, amount, minReturn, pools);
}
/// @notice Same as `uniswapV3SwapTo` but uses `msg.sender` as recipient
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
function uniswapV3Swap(
uint256 amount,
uint256 minReturn,
uint256[] calldata pools
) external payable returns(uint256 returnAmount) {
return uniswapV3SwapTo(msg.sender, amount, minReturn, pools);
}
/// @notice Performs swap using Uniswap V3 exchange. Wraps and unwraps ETH if required.
/// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
/// @param recipient Address that will receive swap funds
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
function uniswapV3SwapTo(
address payable recipient,
uint256 amount,
uint256 minReturn,
uint256[] calldata pools
) public payable returns(uint256 returnAmount) {
uint256 len = pools.length;
require(len > 0, "UNIV3R: empty pools");
uint256 lastIndex = len - 1;
returnAmount = amount;
bool wrapWeth = pools[0] & _WETH_WRAP_MASK > 0;
bool unwrapWeth = pools[lastIndex] & _WETH_UNWRAP_MASK > 0;
if (wrapWeth) {
require(msg.value == amount, "UNIV3R: wrong msg.value");
_WETH.deposit{value: amount}();
} else {
require(msg.value == 0, "UNIV3R: msg.value should be 0");
}
if (len > 1) {
returnAmount = _makeSwap(address(this), wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
for (uint256 i = 1; i < lastIndex; i++) {
returnAmount = _makeSwap(address(this), address(this), pools[i], returnAmount);
}
returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, address(this), pools[lastIndex], returnAmount);
} else {
returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
}
require(returnAmount >= minReturn, "UNIV3R: min return");
if (unwrapWeth) {
_WETH.withdraw(returnAmount);
recipient.sendValue(returnAmount);
}
}
/// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /* data */
) external override {
IERC20 token0;
IERC20 token1;
bytes32 ffFactoryAddress = _FF_FACTORY;
bytes32 poolInitCodeHash = _POOL_INIT_CODE_HASH;
address payer;
assembly { // solhint-disable-line no-inline-assembly
function reRevert() {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
function revertWithReason(m, len) {
mstore(0x00, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x20, 0x0000002000000000000000000000000000000000000000000000000000000000)
mstore(0x40, m)
revert(0, len)
}
let emptyPtr := mload(0x40)
let resultPtr := add(emptyPtr, 0x20)
mstore(emptyPtr, _SELECTORS)
if iszero(staticcall(gas(), caller(), emptyPtr, 0x4, resultPtr, 0x20)) {
reRevert()
}
token0 := mload(resultPtr)
if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x4), 0x4, resultPtr, 0x20)) {
reRevert()
}
token1 := mload(resultPtr)
if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x8), 0x4, resultPtr, 0x20)) {
reRevert()
}
let fee := mload(resultPtr)
let p := emptyPtr
mstore(p, ffFactoryAddress)
p := add(p, 21)
// Compute the inner hash in-place
mstore(p, token0)
mstore(add(p, 32), token1)
mstore(add(p, 64), fee)
mstore(p, keccak256(p, 96))
p := add(p, 32)
mstore(p, poolInitCodeHash)
let pool := and(keccak256(emptyPtr, 85), _ADDRESS_MASK)
if iszero(eq(pool, caller())) {
revertWithReason(0x00000010554e495633523a2062616420706f6f6c000000000000000000000000, 0x54) // UNIV3R: bad pool
}
calldatacopy(emptyPtr, 0x84, 0x20)
payer := mload(emptyPtr)
}
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
} else {
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
}
if (amount1Delta > 0) {
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
} else {
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
function _makeSwap(address recipient, address payer, uint256 pool, uint256 amount) private returns (uint256) {
bool zeroForOne = pool & _ONE_FOR_ZERO_MASK == 0;
if (zeroForOne) {
(, int256 amount1) = IUniswapV3Pool(pool).swap(
recipient,
zeroForOne,
SafeCast.toInt256(amount),
_MIN_SQRT_RATIO,
abi.encode(payer)
);
return SafeCast.toUint256(-amount1);
} else {
(int256 amount0,) = IUniswapV3Pool(pool).swap(
recipient,
zeroForOne,
SafeCast.toInt256(amount),
_MAX_SQRT_RATIO,
abi.encode(payer)
);
return SafeCast.toUint256(-amount0);
}
}
}
// File contracts/interfaces/IClipperExchangeInterface.sol
pragma solidity ^0.7.6;
/// @title Clipper interface subset used in swaps
interface IClipperExchangeInterface {
function sellTokenForToken(IERC20 inputToken, IERC20 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount);
function sellEthForToken(IERC20 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external payable returns (uint256 boughtAmount);
function sellTokenForEth(IERC20 inputToken, address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount);
function theExchange() external returns (address payable);
}
// File contracts/ClipperRouter.sol
pragma solidity ^0.7.6;
/// @title Clipper router that allows to use `ClipperExchangeInterface` for swaps
contract ClipperRouter is EthReceiver, Permitable {
using SafeERC20 for IERC20;
IWETH private immutable _WETH; // solhint-disable-line var-name-mixedcase
IERC20 private constant _ETH = IERC20(address(0));
bytes private constant _INCH_TAG = "1INCH";
IClipperExchangeInterface private immutable _clipperExchange;
address payable private immutable _clipperPool;
constructor(
address weth,
IClipperExchangeInterface clipperExchange
) {
_clipperExchange = clipperExchange;
_clipperPool = clipperExchange.theExchange();
_WETH = IWETH(weth);
}
/// @notice Same as `clipperSwapTo` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// @param recipient Address that will receive swap funds
/// @param srcToken Source token
/// @param dstToken Destination token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
/// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
/// See tests for examples
function clipperSwapToWithPermit(
address payable recipient,
IERC20 srcToken,
IERC20 dstToken,
uint256 amount,
uint256 minReturn,
bytes calldata permit
) external returns(uint256 returnAmount) {
_permit(address(srcToken), permit);
return clipperSwapTo(recipient, srcToken, dstToken, amount, minReturn);
}
/// @notice Same as `clipperSwapTo` but uses `msg.sender` as recipient
/// @param srcToken Source token
/// @param dstToken Destination token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
function clipperSwap(
IERC20 srcToken,
IERC20 dstToken,
uint256 amount,
uint256 minReturn
) external payable returns(uint256 returnAmount) {
return clipperSwapTo(msg.sender, srcToken, dstToken, amount, minReturn);
}
/// @notice Performs swap using Clipper exchange. Wraps and unwraps ETH if required.
/// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
/// @param recipient Address that will receive swap funds
/// @param srcToken Source token
/// @param dstToken Destination token
/// @param amount Amount of source tokens to swap
/// @param minReturn Minimal allowed returnAmount to make transaction commit
function clipperSwapTo(
address payable recipient,
IERC20 srcToken,
IERC20 dstToken,
uint256 amount,
uint256 minReturn
) public payable returns(uint256 returnAmount) {
bool srcETH;
if (srcToken == _WETH) {
require(msg.value == 0, "CL1IN: msg.value should be 0");
_WETH.transferFrom(msg.sender, address(this), amount);
_WETH.withdraw(amount);
srcETH = true;
}
else if (srcToken == _ETH) {
require(msg.value == amount, "CL1IN: wrong msg.value");
srcETH = true;
}
else {
require(msg.value == 0, "CL1IN: msg.value should be 0");
srcToken.safeTransferFrom(msg.sender, _clipperPool, amount);
}
if (srcETH) {
_clipperPool.transfer(amount);
returnAmount = _clipperExchange.sellEthForToken(dstToken, recipient, minReturn, _INCH_TAG);
} else if (dstToken == _WETH) {
returnAmount = _clipperExchange.sellTokenForEth(srcToken, address(this), minReturn, _INCH_TAG);
_WETH.deposit{ value: returnAmount }();
_WETH.transfer(recipient, returnAmount);
} else if (dstToken == _ETH) {
returnAmount = _clipperExchange.sellTokenForEth(srcToken, recipient, minReturn, _INCH_TAG);
} else {
returnAmount = _clipperExchange.sellTokenForToken(srcToken, dstToken, recipient, minReturn, _INCH_TAG);
}
}
}
// File contracts/AggregationRouterV4.sol
pragma solidity ^0.7.6;
contract AggregationRouterV4 is Ownable, EthReceiver, Permitable, UnoswapRouter, UnoswapV3Router, LimitOrderProtocolRFQ, ClipperRouter {
using SafeMath for uint256;
using UniERC20 for IERC20;
using SafeERC20 for IERC20;
uint256 private constant _PARTIAL_FILL = 1 << 0;
uint256 private constant _REQUIRES_EXTRA_ETH = 1 << 1;
struct SwapDescription {
IERC20 srcToken;
IERC20 dstToken;
address payable srcReceiver;
address payable dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
constructor(address weth, IClipperExchangeInterface _clipperExchange)
UnoswapV3Router(weth)
LimitOrderProtocolRFQ(weth)
ClipperRouter(weth, _clipperExchange)
{} // solhint-disable-line no-empty-blocks
/// @notice Performs a swap, delegating all calls encoded in `data` to `caller`. See tests for usage examples
/// @param caller Aggregation executor that executes calls described in `data`
/// @param desc Swap description
/// @param data Encoded calls that `caller` should execute in between of swaps
/// @return returnAmount Resulting token amount
/// @return spentAmount Source token amount
/// @return gasLeft Gas left
function swap(
IAggregationExecutor caller,
SwapDescription calldata desc,
bytes calldata data
)
external
payable
returns (
uint256 returnAmount,
uint256 spentAmount,
uint256 gasLeft
)
{
require(desc.minReturnAmount > 0, "Min return should not be 0");
require(data.length > 0, "data should not be empty");
uint256 flags = desc.flags;
IERC20 srcToken = desc.srcToken;
IERC20 dstToken = desc.dstToken;
bool srcETH = srcToken.isETH();
if (flags & _REQUIRES_EXTRA_ETH != 0) {
require(msg.value > (srcETH ? desc.amount : 0), "Invalid msg.value");
} else {
require(msg.value == (srcETH ? desc.amount : 0), "Invalid msg.value");
}
if (!srcETH) {
_permit(address(srcToken), desc.permit);
srcToken.safeTransferFrom(msg.sender, desc.srcReceiver, desc.amount);
}
{
bytes memory callData = abi.encodePacked(caller.callBytes.selector, bytes12(0), msg.sender, data);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = address(caller).call{value: msg.value}(callData);
if (!success) {
revert(RevertReasonParser.parse(result, "callBytes failed: "));
}
}
spentAmount = desc.amount;
returnAmount = dstToken.uniBalanceOf(address(this));
if (flags & _PARTIAL_FILL != 0) {
uint256 unspentAmount = srcToken.uniBalanceOf(address(this));
if (unspentAmount > 0) {
spentAmount = spentAmount.sub(unspentAmount);
srcToken.uniTransfer(msg.sender, unspentAmount);
}
require(returnAmount.mul(desc.amount) >= desc.minReturnAmount.mul(spentAmount), "Return amount is not enough");
} else {
require(returnAmount >= desc.minReturnAmount, "Return amount is not enough");
}
address payable dstReceiver = (desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver;
dstToken.uniTransfer(dstReceiver, returnAmount);
gasLeft = gasleft();
}
function rescueFunds(IERC20 token, uint256 amount) external onlyOwner {
token.uniTransfer(msg.sender, amount);
}
function destroy() external onlyOwner {
selfdestruct(msg.sender);
}
} | @title Clipper interface subset used in swaps | interface IClipperExchangeInterface {
function sellTokenForToken(IERC20 inputToken, IERC20 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount);
function sellEthForToken(IERC20 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external payable returns (uint256 boughtAmount);
function sellTokenForEth(IERC20 inputToken, address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount);
function theExchange() external returns (address payable);
}
| 12,840,620 | [
1,
15339,
457,
1560,
7931,
1399,
316,
1352,
6679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
15339,
457,
11688,
1358,
288,
203,
565,
445,
357,
80,
1345,
1290,
1345,
12,
45,
654,
39,
3462,
810,
1345,
16,
467,
654,
39,
3462,
876,
1345,
16,
1758,
8027,
16,
2254,
5034,
1131,
38,
9835,
6275,
16,
1731,
745,
892,
9397,
20606,
751,
13,
3903,
1135,
261,
11890,
5034,
800,
9540,
6275,
1769,
203,
565,
445,
357,
80,
41,
451,
1290,
1345,
12,
45,
654,
39,
3462,
876,
1345,
16,
1758,
8027,
16,
2254,
5034,
1131,
38,
9835,
6275,
16,
1731,
745,
892,
9397,
20606,
751,
13,
3903,
8843,
429,
1135,
261,
11890,
5034,
800,
9540,
6275,
1769,
203,
565,
445,
357,
80,
1345,
1290,
41,
451,
12,
45,
654,
39,
3462,
810,
1345,
16,
1758,
8843,
429,
8027,
16,
2254,
5034,
1131,
38,
9835,
6275,
16,
1731,
745,
892,
9397,
20606,
751,
13,
3903,
1135,
261,
11890,
5034,
800,
9540,
6275,
1769,
203,
565,
445,
326,
11688,
1435,
3903,
1135,
261,
2867,
8843,
429,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import { Utils } from './Utils.sol';
import './FunctionsStorage.sol';
// Main contract definition which exposes functionalities to the other service components
contract EtherlessSmart {
// The contract instance used for storing service data (functions, etc...)
FunctionsStorage private fnStorage;
// contract balance internal reference
uint256 private balance = 0;
// fixed cost per function run request
uint256 private serviceCostPerFunctionExecution = 10;
/* EVENTS */
// An event that triggers the server component and requests a remote function execution
event RemoteExec(string _name, string _parameters, string _identifier);
// An event that triggers the client component and delivers the remote function execution result
event RemoteResponse(string _response, string _identifier);
/* END EVENTS */
constructor () public {
// TODO: this should not be here as it's handled by Truffle
fnStorage = new FunctionsStorage();
}
// Returns the contract balance
function getBalance()
public view
returns (uint256) {
return balance;
}
// Returns the list of functions from the storage
function listFunctions()
public
view
returns (FunctionsStorage.Function[] memory functionNames)
{
return fnStorage.getFunctions();
}
// Returns function data specificcaly for the given function name
// If the function name does not exists a function not found error will be triggered
function findFunction(string memory fnToSearch)
public
view
returns (FunctionsStorage.Function memory)
{
FunctionsStorage.Function memory fn = fnStorage.getFunctionDetails(fnToSearch);
// Total cost displayed to the user: function owner-defined cost + service fee per run request
fn.cost = fn.cost + serviceCostPerFunctionExecution;
return fn;
}
// Creates and stores a new function with the given properties for the network user
function createFunction(string memory fnName,
string memory description,
string memory prototype,
string memory remoteResource,
uint256 cost)
public
{
// Checks if the function already exists
if (fnStorage.existsFunction(fnName)){
revert("Function already exists");
}
FunctionsStorage.Function memory fn = FunctionsStorage.Function({
name: fnName,
description: description,
prototype: prototype,
cost: cost,
owner: msg.sender,
remoteResource: remoteResource
});
fnStorage.storeFunction(fn);
}
// Starts the remote function execution process
// Identifiers are strings that identify the execution request
function runFunction(string memory fnName, string memory paramers, string memory identifier)
public
payable
{
require(
bytes(paramers).length > 0,
"Invalid paramers serialization (length = 0)"
); // length conversion valid only for some encodings
// get function data
FunctionsStorage.Function memory fnRequested = fnStorage.getFunctionDetails(fnName);
// check if correct ether amount sent by caller
uint256 fnCostToRun = costOfFunction(fnName);
uint256 amountSentByCaller = msg.value; // msg.value is the amount of ether send by the user to the contract with this method call
require(
amountSentByCaller == fnCostToRun,
Utils.concat(
"Incorrect transaction amount sent by caller ",
Utils.uint2str(amountSentByCaller)
)
);
balance += amountSentByCaller;
// move function cost amount to the owner of the function
moveCurrencies(fnRequested.owner, fnRequested.cost);
// emits the execution request event
// the server component will pick this and run the funciton
emit RemoteExec(fnRequested.remoteResource, paramers, identifier);
}
// Updates a given property of a function to a new value
// Only function owners can change properties
function setFunctionProperty(string memory fnName,
string memory parameter,
string memory substitute)
public
{
FunctionsStorage.Function memory fn = findFunction(fnName);
if(msg.sender != fn.owner){
revert('You are not the owner of the function!');
}
fnStorage.setFunctionProperty(fnName, parameter, substitute);
}
// Deletes a function from the storage
// Only function owners can delete their funcitons
function deleteFunction(string memory nameFunction)
public
{
FunctionsStorage.Function memory fn = findFunction(nameFunction);
if(msg.sender != fn.owner){
revert('You are not the owner of the function!');
}
fnStorage.deleteFunction(fn.owner, nameFunction);
}
// Return the remote resource identifier
// Only function owners can request the resource identifier for their functions
function getArn(string memory fnName)
public
view
returns (string memory arn)
{
FunctionsStorage.Function memory fn = findFunction(fnName);
if(msg.sender != fn.owner){
revert('You are not the owner of the function!');
}
return fn.remoteResource;
}
// Transfers Ether from the contract to a given user
function moveCurrencies(address payable receiver, uint256 amount)
private
{
balance -= amount;
receiver.transfer(amount);
}
// Sends an execution result to the client component
// Identifiers are strings that identify the execution request
function sendResponse(string memory result, string memory identifier) public {
emit RemoteResponse(result, identifier);
}
// Returns the cost for running a function for the end user
function costOfFunction(string memory fnName)
public
view
returns (uint256 cost)
{
return fnStorage.costOfFunction(fnName) + serviceCostPerFunctionExecution;
}
}
| Sends an execution result to the client component Identifiers are strings that identify the execution request | function sendResponse(string memory result, string memory identifier) public {
emit RemoteResponse(result, identifier);
}
| 2,550,681 | [
1,
10501,
392,
4588,
563,
358,
326,
1004,
1794,
13128,
3383,
854,
2064,
716,
9786,
326,
4588,
590,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1366,
1064,
12,
1080,
3778,
563,
16,
533,
3778,
2756,
13,
1071,
288,
203,
3639,
3626,
6304,
1064,
12,
2088,
16,
2756,
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
] |
pragma solidity ^0.5.0;
import "./GhostOwnership.sol";
import "./SpecialAuction.sol";
import "./SaleAuction.sol";
contract GhostAuction is GhostOwnership {
// address of special auction that control sale of special ghost.
SpecialAuction public specialAuction;
// address of sale auction that control sale of ghost between users.
SaleAuction public saleAuction;
constructor (address _specialAddress, address _saleAddress) public GhostOwnership(msg.sender) {
SpecialAuction candidateSpecialContract = SpecialAuction(_specialAddress);
specialAuction = candidateSpecialContract;
SaleAuction candidateSaleContract = SaleAuction(_saleAddress);
saleAuction = candidateSaleContract;
}
// @notice sets reference to the special auction contract.
// @dev This function is just called by CEO.
function setSpecialAuctionAddress(address _contractAddress) external onlyCEO {
SpecialAuction candidateContract = SpecialAuction(_contractAddress);
specialAuction = candidateContract;
}
// @notice create special auction by only CEO.
// @param _tokenId - Ghost ID of special ghost.
function createSpecialAuction(uint256 _tokenId) external onlyCEO {
require(_owns(msg.sender, _tokenId));
// TODO: initiate duration
uint256 _duration = 3 seconds;
_approve(address(specialAuction), _tokenId);
specialAuction.createAuction(_tokenId, msg.sender, _duration);
}
// @notice sets reference to the sale auction contract.
// @dev This function is just called by CEO.
function setSaleAuctionAddress(address _contractAddress) external onlyCEO {
SaleAuction candidateContract = SaleAuction(_contractAddress);
saleAuction = candidateContract;
}
// @notice create sale auction.
// @param _tokenId - Ghost ID to exchange and put on auction.
// @param _buyer - address of person to buy ghost.
// @param _amount - offered price of this ghost.
function createSaleAuction(uint256 _tokenId, address payable _buyer, uint256 _amount) external {
require(_owns(msg.sender, _tokenId));
require(_buyer != address(0));
require(_amount > uint256(0));
_approve(address(saleAuction), _tokenId);
saleAuction.createAuction(_tokenId, msg.sender, _buyer, _amount);
}
}
| @notice create sale auction. @param _tokenId - Ghost ID to exchange and put on auction. @param _buyer - address of person to buy ghost. @param _amount - offered price of this ghost. | function createSaleAuction(uint256 _tokenId, address payable _buyer, uint256 _amount) external {
require(_owns(msg.sender, _tokenId));
require(_buyer != address(0));
require(_amount > uint256(0));
_approve(address(saleAuction), _tokenId);
saleAuction.createAuction(_tokenId, msg.sender, _buyer, _amount);
}
| 5,444,531 | [
1,
2640,
272,
5349,
279,
4062,
18,
225,
389,
2316,
548,
300,
611,
2564,
1599,
358,
7829,
471,
1378,
603,
279,
4062,
18,
225,
389,
70,
16213,
300,
1758,
434,
6175,
358,
30143,
314,
2564,
18,
225,
389,
8949,
300,
10067,
329,
6205,
434,
333,
314,
2564,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
752,
30746,
37,
4062,
12,
11890,
5034,
389,
2316,
548,
16,
1758,
8843,
429,
389,
70,
16213,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
24899,
995,
87,
12,
3576,
18,
15330,
16,
389,
2316,
548,
10019,
203,
3639,
2583,
24899,
70,
16213,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
8949,
405,
2254,
5034,
12,
20,
10019,
203,
203,
3639,
389,
12908,
537,
12,
2867,
12,
87,
5349,
37,
4062,
3631,
389,
2316,
548,
1769,
203,
203,
3639,
272,
5349,
37,
4062,
18,
2640,
37,
4062,
24899,
2316,
548,
16,
1234,
18,
15330,
16,
389,
70,
16213,
16,
389,
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
] |
/**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
abcLotto: a Block Chain Lottery
Don't trust anyone but the CODE!
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*
* This product is protected under license. Any unauthorized copy, modification, or use without
* express written consent from the creators is prohibited.
*/
/**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- this is a 5/16 lotto, choose 5 numbers in 1-16.
- per ticket has two chance to win the jackpot, daily and weekly.
- daily jackpot need choose 5 right numbers.
- weekly jackpot need choose 5 rights numbers with right sequence.
- you must have an inviter then to buy.
- act as inviter will get bonus.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
pragma solidity ^0.4.20;
/**
* @title abc address resolver interface.
*/
contract abcResolverI{
function getWalletAddress() public view returns (address);
function getBookAddress() public view returns (address);
function getControllerAddress() public view returns (address);
}
/**
* @title inviter book interface.
*/
contract inviterBookI{
function isRoot(address addr) public view returns(bool);
function hasInviter(address addr) public view returns(bool);
function setInviter(address addr, string inviter) public;
function pay(address addr) public payable;
}
/**
* @title abcLotto : data structure, buy and reward functions.
* @dev a decentralized lottery application.
*/
contract abcLotto{
using SafeMath for *;
//global varibles
abcResolverI public resolver;
address public controller;
inviterBookI public book;
address public wallet;
uint32 public currentRound; //current round, plus 1 every day;
uint8 public currentState; //1 - bet period, 2 - freeze period, 3 - draw period.
uint32[] public amounts; //buy amount per round.
uint32[] public addrs; //buy addresses per round.
bool[] public drawed; //lottery draw finished mark.
uint public rollover = 0;
uint[] public poolUsed;
//constant
uint constant ABC_GAS_CONSUME = 50; //this abc Dapp cost, default 50/1000.
uint constant INVITER_FEE = 100; // inviter fee, default 100/1000;
uint constant SINGLE_BET_PRICE = 50000000000000000; // single bet price is 0.05 ether.
uint constant THISDAPP_DIV = 1000;
uint constant POOL_ALLOCATION_WEEK = 500;
uint constant POOL_ALLOCATION_JACKPOT = 618;
uint constant MAX_BET_AMOUNT = 100; //per address can bet amount must be less than 100 per round.
uint8 constant MAX_BET_NUM = 16;
uint8 constant MIN_BET_NUM = 1;
//data structures
struct UnitBet{
uint8[5] _nums;
bool _payed1; //daily
bool _payed2; //weekly
}
struct AddrBets{
UnitBet[] _unitBets;
}
struct RoundBets{
mapping (address=>AddrBets) _roundBets;
}
RoundBets[] allBets;
struct BetKeyEntity{
mapping (bytes5=>uint32) _entity;
}
BetKeyEntity[] betDaily;
BetKeyEntity[] betWeekly;
struct Jackpot{
uint8[5] _results;
}
Jackpot[] dailyJackpot;
Jackpot[] weeklyJackpot;
//events
event OnBuy(address user, uint32 round, uint32 index, uint8[5] nums);
event OnRewardDaily(address user, uint32 round, uint32 index, uint reward);
event OnRewardWeekly(address user, uint32 round, uint32 index,uint reward);
event OnRewardDailyFailed(address user, uint32 round, uint32 index);
event OnRewardWeeklyFailed(address user, uint32 round, uint32 index);
event OnNewRound(uint32 round);
event OnFreeze(uint32 round);
event OnUnFreeze(uint32 round);
event OnDrawStart(uint32 round);
event OnDrawFinished(uint32 round, uint8[5] jackpot);
event BalanceNotEnough();
//modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
modifier onlyBetPeriod {
require(currentState == 1);
_;
}
modifier onlyHuman {
require(msg.sender == tx.origin);
_;
}
//check contract interface, are they upgrated?
modifier abcInterface {
if((address(resolver)==0)||(getCodeSize(address(resolver))==0)){
if(abc_initNetwork()){
wallet = resolver.getWalletAddress();
book = inviterBookI(resolver.getBookAddress());
controller = resolver.getControllerAddress();
}
}
else{
if(wallet != resolver.getWalletAddress())
wallet = resolver.getWalletAddress();
if(address(book) != resolver.getBookAddress())
book = inviterBookI(resolver.getBookAddress());
if(controller != resolver.getControllerAddress())
controller = resolver.getControllerAddress();
}
_;
}
/**
* @dev fallback funtion, this contract don't accept ether directly.
*/
function() public payable {
revert();
}
/**
* @dev init address resolver.
*/
function abc_initNetwork() internal returns(bool) {
//mainnet
if (getCodeSize(0xde4413799c73a356d83ace2dc9055957c0a5c335)>0){
resolver = abcResolverI(0xde4413799c73a356d83ace2dc9055957c0a5c335);
return true;
}
//others ...
return false;
}
/**
* @dev get code size of appointed address.
*/
function getCodeSize(address _addr) internal view returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
//+++++++++++++++++++++++++ public operation functions +++++++++++++++++++++++++++++++++++++
/**
* @dev buy: buy a new ticket.
*/
function buy(uint8[5] nums, string inviter)
public
payable
onlyBetPeriod
onlyHuman
abcInterface
returns (uint)
{
//check number range 1-16, no repeat number.
if(!isValidNum(nums)) revert();
//doesn't offer enough value.
if(msg.value < SINGLE_BET_PRICE) revert();
//check daily amount is less than MAX_BET_AMOUNT
uint _am = allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length.add(1);
if( _am > MAX_BET_AMOUNT) revert();
//update storage varibles.
amounts[currentRound-1]++;
if(allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length <= 0)
addrs[currentRound-1]++;
//insert bet record.
UnitBet memory _bet;
_bet._nums = nums;
_bet._payed1 = false;
_bet._payed2 = false;
allBets[currentRound-1]._roundBets[msg.sender]._unitBets.push(_bet);
//increase key-value records.
bytes5 _key;
_key = generateCombinationKey(nums);
betDaily[currentRound-1]._entity[_key]++;
_key = generatePermutationKey(nums);
uint32 week = (currentRound-1) / 7;
betWeekly[week]._entity[_key]++;
//refund extra value.
if(msg.value > SINGLE_BET_PRICE){
msg.sender.transfer(msg.value.sub(SINGLE_BET_PRICE));
}
//has inviter?
if(book.hasInviter(msg.sender) || book.isRoot(msg.sender)){
book.pay.value(SINGLE_BET_PRICE.mul(INVITER_FEE).div(THISDAPP_DIV))(msg.sender);
}
else{
book.setInviter(msg.sender, inviter);
book.pay.value(SINGLE_BET_PRICE.mul(INVITER_FEE).div(THISDAPP_DIV))(msg.sender);
}
//emit event
emit OnBuy(msg.sender, currentRound, uint32(allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length), nums);
return allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length;
}
/**
* @dev rewardDaily: apply for daily reward.
*/
function rewardDaily(uint32 round, uint32 index)
public
onlyBetPeriod
onlyHuman
returns(uint)
{
require(round>0 && round<=currentRound);
require(drawed[round-1]);
require(index>0 && index<=allBets[round-1]._roundBets[msg.sender]._unitBets.length);
require(!allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1);
uint8[5] memory nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums;
bytes5 key = generateCombinationKey(nums);
bytes5 jackpot = generateCombinationKey(dailyJackpot[round-1]._results);
if(key != jackpot) return;
uint win_amount = betDaily[round-1]._entity[key];
if(win_amount <= 0) return;
uint amount = amounts[round-1];
uint total = SINGLE_BET_PRICE.mul(amount).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(THISDAPP_DIV - POOL_ALLOCATION_WEEK).div(THISDAPP_DIV);
uint pay = total.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount);
//pay action
if(pay > address(this).balance){
emit BalanceNotEnough();
revert();
}
allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1 = true;
if(!msg.sender.send(pay)){
emit OnRewardDailyFailed(msg.sender, round, index);
revert();
}
emit OnRewardDaily(msg.sender, round, index, pay);
return pay;
}
/**
* @dev rewardWeekly: apply for weekly reward.
*/
function rewardWeekly(uint32 round, uint32 index)
public
onlyBetPeriod
onlyHuman
returns(uint)
{
require(round>0 && round<=currentRound);
require(drawed[round-1]);
require(index>0 && index<=allBets[round-1]._roundBets[msg.sender]._unitBets.length);
require(!allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2);
uint32 week = (round-1)/7 + 1;
uint8[5] memory nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums;
bytes5 key = generatePermutationKey(nums);
bytes5 jackpot = generatePermutationKey(weeklyJackpot[week-1]._results);
if(key != jackpot) return;
uint32 win_amount = betWeekly[week-1]._entity[key];
if(win_amount <= 0) return;
uint pay = poolUsed[week-1].div(win_amount);
//pay action
if(pay > address(this).balance){
emit BalanceNotEnough();
return;
}
allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2 = true;
if(!msg.sender.send(pay)){
emit OnRewardWeeklyFailed(msg.sender, round, index);
revert();
}
emit OnRewardWeekly(msg.sender, round, index, pay);
return pay;
}
//+++++++++++++++++++++++++ pure or view functions +++++++++++++++++++++++++++++++++++++
/**
* @dev getSingleBet: get self's bet record.
*/
function getSingleBet(uint32 round, uint32 index)
public
view
returns(uint8[5] nums, bool payed1, bool payed2)
{
if(round == 0 || round > currentRound) return;
uint32 iLen = uint32(allBets[round-1]._roundBets[msg.sender]._unitBets.length);
if(iLen <= 0) return;
if(index == 0 || index > iLen) return;
nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums;
payed1 = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1;
payed2 = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2;
}
/**
* @dev getAmountDailybyNum: get the daily bet amount of a set of numbers.
*/
function getAmountDailybyNum(uint32 round, uint8[5] nums)
public
view
returns(uint32)
{
if(round == 0 || round > currentRound) return 0;
bytes5 _key = generateCombinationKey(nums);
return betDaily[round-1]._entity[_key];
}
/**
* @dev getAmountWeeklybyNum: get the weekly bet amount of a set of numbers.
*/
function getAmountWeeklybyNum(uint32 week, uint8[5] nums)
public
view
returns(uint32)
{
if(week == 0 || currentRound < (week-1)*7) return 0;
bytes5 _key = generatePermutationKey(nums);
return betWeekly[week-1]._entity[_key];
}
/**
* @dev getDailyJackpot: some day's Jackpot.
*/
function getDailyJackpot(uint32 round)
public
view
returns(uint8[5] jackpot, uint32 amount)
{
if(round == 0 || round > currentRound) return;
jackpot = dailyJackpot[round-1]._results;
amount = getAmountDailybyNum(round, jackpot);
}
/**
* @dev getWeeklyJackpot: some week's Jackpot.
*/
function getWeeklyJackpot(uint32 week)
public
view
returns(uint8[5] jackpot, uint32 amount)
{
if(week == 0 || week > currentRound/7) return;
jackpot = weeklyJackpot[week - 1]._results;
amount = getAmountWeeklybyNum(week, jackpot);
}
//+++++++++++++++++++++++++ controller functions +++++++++++++++++++++++++++++++++++++
/**
* @dev start new round.
*/
function nextRound()
abcInterface
public
onlyController
{
//current round must be drawed.
if(currentRound > 0)
require(drawed[currentRound-1]);
currentRound++;
currentState = 1;
amounts.length++;
addrs.length++;
drawed.length++;
RoundBets memory _rb;
allBets.push(_rb);
BetKeyEntity memory _en1;
betDaily.push(_en1);
Jackpot memory _b1;
dailyJackpot.push(_b1);
//if is a weekend or beginning.
if((currentRound-1) % 7 == 0){
BetKeyEntity memory _en2;
betWeekly.push(_en2);
Jackpot memory _b2;
weeklyJackpot.push(_b2);
poolUsed.length++;
}
emit OnNewRound(currentRound);
}
/**
* @dev freeze: enter freeze period.
*/
function freeze()
abcInterface
public
onlyController
{
currentState = 2;
emit OnFreeze(currentRound);
}
/**
* @dev freeze: enter freeze period.
*/
function unfreeze()
abcInterface
public
onlyController
{
require(currentState == 2);
currentState = 1;
emit OnUnFreeze(currentRound);
}
/**
* @dev draw: enter freeze period.
*/
function draw()
abcInterface
public
onlyController
{
require(!drawed[currentRound-1]);
currentState = 3;
emit OnDrawStart(currentRound);
}
/**
* @dev controller have generated and set Jackpot.
*/
function setJackpot(uint8[5] jackpot)
abcInterface
public
onlyController
{
require(currentState==3 && !drawed[currentRound-1]);
//check jackpot range 1-16, no repeat number.
if(!isValidNum(jackpot)) return;
uint _fee = 0;
//mark daily entity's prize.-----------------------------------------------------------------------------------
uint8[5] memory _jackpot1 = sort(jackpot);
dailyJackpot[currentRound-1]._results = _jackpot1;
bytes5 _key = generateCombinationKey(_jackpot1);
uint total = SINGLE_BET_PRICE.mul(amounts[currentRound-1]).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(THISDAPP_DIV - POOL_ALLOCATION_WEEK).div(THISDAPP_DIV);
uint win_amount = uint(betDaily[currentRound-1]._entity[_key]);
uint _bonus_sum;
if( win_amount <= 0){
rollover = rollover.add(total);
}
else{
_bonus_sum = total.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount).mul(win_amount);
_fee = _fee.add(total.sub(_bonus_sum));
}
//end mark.-----------------------------------------------------------------------------------
//mark weekly entity's prize.---------------------------------------------------------------------------------------
if((currentRound > 0) && (currentRound % 7 == 0)){
uint32 _week = currentRound/7;
weeklyJackpot[_week-1]._results = jackpot;
_key = generatePermutationKey(jackpot);
uint32 _amounts = getAmountWeekly(_week);
total = SINGLE_BET_PRICE.mul(_amounts).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(POOL_ALLOCATION_WEEK).div(THISDAPP_DIV);
win_amount = uint(betWeekly[_week-1]._entity[_key]);
if(win_amount > 0){
total = total.add(rollover);
_bonus_sum = total.mul(POOL_ALLOCATION_JACKPOT).div(THISDAPP_DIV);
rollover = total.sub(_bonus_sum);
poolUsed[_week-1] = _bonus_sum.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount).mul(win_amount);
_fee = _fee.add(_bonus_sum.sub(poolUsed[_week-1]));
}
else{
rollover = rollover.add(total);
}
}
//end mark.-----------------------------------------------------------------------------------
drawed[currentRound-1] = true;
wallet.transfer(_fee);
emit OnDrawFinished(currentRound, jackpot);
}
//+++++++++++++++++++++++++ internal functions +++++++++++++++++++++++++++++++++++++
/**
* @dev getAmountWeekly: the bet amount of a week.
*/
function getAmountWeekly(uint32 week) internal view returns(uint32){
if(week == 0 || currentRound < (week-1)*7) return 0;
uint32 _ret;
uint8 i;
if(currentRound > week*7){
for(i=0; i<7; i++){
_ret += amounts[(week-1)*7+i];
}
}
else{
uint8 j = uint8((currentRound-1) % 7);
for(i=0;i<=j;i++){
_ret += amounts[(week-1)*7+i];
}
}
return _ret;
}
/**
* @dev check if is a valid set of number.
* @param nums : chosen number.
*/
function isValidNum(uint8[5] nums) internal pure returns(bool){
for(uint i = 0; i<5; i++){
if(nums[i] < MIN_BET_NUM || nums[i] > MAX_BET_NUM)
return false;
}
if(hasRepeat(nums)) return false;
return true;
}
/**
* @dev sort 5 numbers.
* don't want to change input numbers sequence, so copy it at first.
* @param nums : input numbers.
*/
function sort(uint8[5] nums) internal pure returns(uint8[5]){
uint8[5] memory _nums;
uint8 i;
for(i=0;i<5;i++)
_nums[i] = nums[i];
uint8 j;
uint8 temp;
for(i =0; i<5-1; i++){
for(j=0; j<5-i-1;j++){
if(_nums[j]>_nums[j+1]){
temp = _nums[j];
_nums[j] = _nums[j+1];
_nums[j+1] = temp;
}
}
}
return _nums;
}
/**
* @dev does has repeat number?
* @param nums : input numbers.
*/
function hasRepeat(uint8[5] nums) internal pure returns(bool){
uint8 i;
uint8 j;
for(i =0; i<5-1; i++){
for(j=i; j<5-1;j++){
if(nums[i]==nums[j+1]) return true;
}
}
return false;
}
/**
* @dev generate Combination key, need sort at first.
*/
function generateCombinationKey(uint8[5] nums) internal pure returns(bytes5){
uint8[5] memory temp = sort(nums);
bytes5 ret;
ret = (ret | byte(temp[4])) >> 8;
ret = (ret | byte(temp[3])) >> 8;
ret = (ret | byte(temp[2])) >> 8;
ret = (ret | byte(temp[1])) >> 8;
ret = ret | byte(temp[0]);
return ret;
}
/**
* @dev generate Permutation key.
*/
function generatePermutationKey(uint8[5] nums) internal pure returns(bytes5){
bytes5 ret;
ret = (ret | byte(nums[4])) >> 8;
ret = (ret | byte(nums[3])) >> 8;
ret = (ret | byte(nums[2])) >> 8;
ret = (ret | byte(nums[1])) >> 8;
ret = ret | byte(nums[0]);
return ret;
}
}
/**
* @title SafeMath : it's from openzeppelin.
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Subtracts two 32 bit numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub_32(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Adds two 32 bit numbers, throws on overflow.
*/
function add_32(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
} | * @dev getAmountWeeklybyNum: get the weekly bet amount of a set of numbers./ | function getAmountWeeklybyNum(uint32 week, uint8[5] nums)
public
view
returns(uint32)
{
if(week == 0 || currentRound < (week-1)*7) return 0;
bytes5 _key = generatePermutationKey(nums);
return betWeekly[week-1]._entity[_key];
}
| 7,314,913 | [
1,
588,
6275,
6630,
715,
1637,
2578,
30,
336,
326,
4860,
715,
2701,
3844,
434,
279,
444,
434,
5600,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
24418,
6630,
715,
1637,
2578,
12,
11890,
1578,
4860,
16,
2254,
28,
63,
25,
65,
21060,
13,
7010,
3639,
1071,
7010,
3639,
1476,
7010,
3639,
1135,
12,
11890,
1578,
13,
203,
565,
288,
203,
540,
309,
12,
10741,
422,
374,
747,
783,
11066,
411,
261,
10741,
17,
21,
17653,
27,
13,
327,
374,
31,
203,
1850,
203,
540,
1731,
25,
389,
856,
273,
2103,
9123,
9245,
653,
12,
21180,
1769,
203,
540,
327,
2701,
6630,
715,
63,
10741,
17,
21,
65,
6315,
1096,
63,
67,
856,
15533,
203,
377,
289,
203,
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
] |
./partial_match/3/0xfAEF1e55792b3825a58F980bF74bb34f430F6576/sources/ENVContract.sol | FEE CONTROLLER EVENTS | event FeeCollected(address indexed from, address indexed to, uint256 value);
| 5,230,754 | [
1,
8090,
41,
8020,
25353,
9964,
55,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
871,
30174,
10808,
329,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./MultiRewardsLiquidityMiningManager.sol";
import "./TimeLockPool.sol";
import "./MultiRewardsTimeLockPool.sol";
/// @dev reader contract to easily fetch all relevant info for an account
contract MultiRewardsView {
struct Data {
uint256 pendingRewards;
Pool[] pools;
Pool escrowPool;
uint256 totalWeight;
}
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
uint256 multiplier;
}
struct Pool {
address poolAddress;
uint256 totalPoolShares;
address depositToken;
uint256 accountPendingRewards;
uint256 accountClaimedRewards;
uint256 accountTotalDeposit;
uint256 accountPoolShares;
uint256 weight;
Deposit[] deposits;
}
MultiRewardsLiquidityMiningManager public immutable liquidityMiningManager;
TimeLockPool public immutable escrowPool;
constructor(address _liquidityMiningManager, address _escrowPool) {
liquidityMiningManager = MultiRewardsLiquidityMiningManager(_liquidityMiningManager);
escrowPool = TimeLockPool(_escrowPool);
}
function fetchData(address _account) external view returns (Data memory result) {
uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond();
uint256 lastDistribution = liquidityMiningManager.lastDistribution();
uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution);
result.pendingRewards = pendingRewards;
result.totalWeight = liquidityMiningManager.totalWeight();
MultiRewardsLiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools();
result.pools = new Pool[](pools.length);
for(uint256 i = 0; i < pools.length; i ++) {
MultiRewardsTimeLockPool poolContract = MultiRewardsTimeLockPool(address(pools[i].poolContract));
address reward = address(liquidityMiningManager.reward());
result.pools[i] = Pool({
poolAddress: address(pools[i].poolContract),
totalPoolShares: poolContract.totalSupply(),
depositToken: address(poolContract.depositToken()),
accountPendingRewards: poolContract.withdrawableRewardsOf(reward, _account),
accountClaimedRewards: poolContract.withdrawnRewardsOf(reward, _account),
accountTotalDeposit: poolContract.getTotalDeposit(_account),
accountPoolShares: poolContract.balanceOf(_account),
weight: pools[i].weight,
deposits: new Deposit[](poolContract.getDepositsOfLength(_account))
});
MultiRewardsTimeLockPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account);
for(uint256 j = 0; j < result.pools[i].deposits.length; j ++) {
MultiRewardsTimeLockPool.Deposit memory deposit = deposits[j];
result.pools[i].deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: poolContract.getMultiplier(deposit.end - deposit.start)
});
}
}
result.escrowPool = Pool({
poolAddress: address(escrowPool),
totalPoolShares: escrowPool.totalSupply(),
depositToken: address(escrowPool.depositToken()),
accountPendingRewards: escrowPool.withdrawableRewardsOf(_account),
accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account),
accountTotalDeposit: escrowPool.getTotalDeposit(_account),
accountPoolShares: escrowPool.balanceOf(_account),
weight: 0,
deposits: new Deposit[](escrowPool.getDepositsOfLength(_account))
});
TimeLockPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account);
for(uint256 j = 0; j < result.escrowPool.deposits.length; j ++) {
TimeLockPool.Deposit memory deposit = deposits[j];
result.escrowPool.deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: escrowPool.getMultiplier(deposit.end - deposit.start)
});
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IMultiRewardsBasePool.sol";
import "./base/TokenSaver.sol";
contract MultiRewardsLiquidityMiningManager is TokenSaver {
using SafeERC20 for IERC20;
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE");
uint256 public MAX_POOL_COUNT = 10;
IERC20 immutable public reward;
address immutable public rewardSource;
uint256 public rewardPerSecond; //total reward amount per second
uint256 public lastDistribution; //when rewards were last pushed
uint256 public totalWeight;
mapping(address => bool) public poolAdded;
Pool[] public pools;
struct Pool {
IMultiRewardsBasePool poolContract;
uint256 weight;
}
modifier onlyGov {
require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied");
_;
}
modifier onlyRewardDistributor {
require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied");
_;
}
event PoolAdded(address indexed pool, uint256 weight);
event PoolRemoved(uint256 indexed poolId, address indexed pool);
event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight);
event RewardsPerSecondSet(uint256 rewardsPerSecond);
event RewardsDistributed(address _from, uint256 indexed _amount);
constructor(address _reward, address _rewardSource) {
require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set");
require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set");
reward = IERC20(_reward);
rewardSource = _rewardSource;
}
function addPool(address _poolContract, uint256 _weight) external onlyGov {
distributeRewards();
require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set");
require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added");
require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached");
// add pool
pools.push(Pool({
poolContract: IMultiRewardsBasePool(_poolContract),
weight: _weight
}));
poolAdded[_poolContract] = true;
// increase totalWeight
totalWeight += _weight;
// Approve max token amount
reward.safeApprove(_poolContract, type(uint256).max);
emit PoolAdded(_poolContract, _weight);
}
function removePool(uint256 _poolId) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist");
distributeRewards();
address poolAddress = address(pools[_poolId].poolContract);
// decrease totalWeight
totalWeight -= pools[_poolId].weight;
// remove pool
pools[_poolId] = pools[pools.length - 1];
pools.pop();
poolAdded[poolAddress] = false;
// Approve 0 token amount
reward.safeApprove(poolAddress, 0);
emit PoolRemoved(_poolId, poolAddress);
}
function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist");
distributeRewards();
Pool storage pool = pools[_poolId];
totalWeight -= pool.weight;
totalWeight += _newWeight;
pool.weight = _newWeight;
emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight);
}
function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov {
distributeRewards();
rewardPerSecond = _rewardPerSecond;
emit RewardsPerSecondSet(_rewardPerSecond);
}
function distributeRewards() public onlyRewardDistributor {
uint256 timePassed = block.timestamp - lastDistribution;
uint256 totalRewardAmount = rewardPerSecond * timePassed;
lastDistribution = block.timestamp;
// return if pool length == 0
if(pools.length == 0) {
return;
}
// return if accrued rewards == 0
if(totalRewardAmount == 0) {
return;
}
reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount);
for(uint256 i = 0; i < pools.length; i ++) {
Pool memory pool = pools[i];
uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight;
// Ignore tx failing to prevent a single pool from halting reward distribution
address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, address(reward), poolRewardAmount));
}
uint256 leftOverReward = reward.balanceOf(address(this));
// send back excess but ignore dust
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
emit RewardsDistributed(_msgSender(), totalRewardAmount);
}
function getPools() external view returns(Pool[] memory result) {
return pools;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/BasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract TimeLockPool is BasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 10 minutes;
uint256 public constant MAX_LOCK_DURATION = 36500 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration,
uint256 _maxBonus,
uint256 _maxLockDuration
) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) {
require(_maxLockDuration <= MAX_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be less than or equal to maximum lock duration");
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/MultiRewardsBasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract MultiRewardsTimeLockPool is MultiRewardsBasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 30 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations,
uint256 _maxBonus,
uint256 _maxLockDuration
) MultiRewardsBasePool(_name, _symbol, _depositToken, _rewardTokens, _escrowPools, _escrowPortions, _escrowDurations) {
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IMultiRewardsBasePool {
function distributeRewards(address _reward, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract TokenSaver is AccessControlEnumerable {
using SafeERC20 for IERC20;
bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE");
event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount);
modifier onlyTokenSaver() {
require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver {
IERC20(_token).safeTransfer(_receiver, _amount);
emit TokenSaved(_msgSender(), _receiver, _token, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractRewards.sol";
import "./TokenSaver.sol";
abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
IERC20 public immutable depositToken;
IERC20 public immutable rewardToken;
ITimeLockPool public immutable escrowPool;
uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100%
uint256 public immutable escrowDuration; // escrow duration in seconds
event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) {
require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%");
require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set");
depositToken = IERC20(_depositToken);
rewardToken = IERC20(_rewardToken);
escrowPool = ITimeLockPool(_escrowPool);
escrowPortion = _escrowPortion;
escrowDuration = _escrowDuration;
if(_rewardToken != address(0) && _escrowPool != address(0)) {
IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max);
}
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
_correctPoints(_account, -(_amount.toInt256()));
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
_correctPoints(_account, _amount.toInt256());
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
_correctPointsForTransfer(_from, _to, _value);
}
function distributeRewards(uint256 _amount) external override nonReentrant {
rewardToken.safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_amount);
}
function claimRewards(address _receiver) external {
uint256 rewardAmount = _prepareCollect(_msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ITimeLockPool {
function deposit(uint256 _amount, uint256 _duration, address _receiver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-ERC20Permit.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IBasePool {
function distributeRewards(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractRewards is IAbstractRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
uint256 public pointsPerShare;
mapping(address => int256) public pointsCorrection;
mapping(address => uint256) public withdrawnRewards;
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_account) - withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _account) public view override returns (uint256) {
return withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _account) public view override returns (uint256) {
return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(uint256 _amount) internal {
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _account) internal returns (uint256) {
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend;
emit RewardsWithdrawn(_account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal {
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare * _shares).toInt256();
pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection;
pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection;
emit PointsCorrectionUpdated(_from, pointsCorrection[_from]);
emit PointsCorrectionUpdated(_to, pointsCorrection[_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare`.
*/
function _correctPoints(address _account, int256 _shares) internal {
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (pointsPerShare.toInt256()));
emit PointsCorrectionUpdated(_account, pointsCorrection[_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAbstractRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IMultiRewardsBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractMultiRewards.sol";
import "./TokenSaver.sol";
abstract contract MultiRewardsBasePool is ERC20Votes, AbstractMultiRewards, IMultiRewardsBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
IERC20 public immutable depositToken;
address[] public rewardTokens;
mapping(address => bool) public rewardTokensList;
mapping(address => address) public escrowPools;
mapping(address => uint256) public escrowPortions; // how much is escrowed 1e18 == 100%
mapping(address => uint256) public escrowDurations; // escrow duration in seconds
event RewardsClaimed(address indexed _reward, address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractMultiRewards(balanceOf, totalSupply) {
require(_depositToken != address(0), "MultiRewardsBasePool.constructor: Deposit token must be set");
require(_rewardTokens.length == _escrowPools.length, "MultiRewardsBasePool.constructor: reward tokens and escrow pools length mismatch");
require(_rewardTokens.length == _escrowPortions.length, "MultiRewardsBasePool.constructor: reward tokens and escrow portions length mismatch");
require(_rewardTokens.length == _escrowDurations.length, "MultiRewardsBasePool.constructor: reward tokens and escrow durations length mismatch");
depositToken = IERC20(_depositToken);
for (uint i=0; i<_rewardTokens.length; i++) {
address rewardToken = _rewardTokens[i];
require(rewardToken != address(0), "MultiRewardsBasePool.constructor: reward token cannot be zero address");
address escrowPool = _escrowPools[i];
uint256 escrowPortion = _escrowPortions[i];
require(escrowPortion <= 1e18, "MultiRewardsBasePool.constructor: Cannot escrow more than 100%");
uint256 escrowDuration = _escrowDurations[i];
if (!rewardTokensList[rewardToken]) {
rewardTokensList[rewardToken] = true;
rewardTokens.push(rewardToken);
escrowPools[rewardToken] = escrowPool;
escrowPortions[rewardToken] = escrowPortion;
escrowDurations[rewardToken] = escrowDuration;
if(rewardToken != address(0) && escrowPool != address(0)) {
IERC20(rewardToken).safeApprove(escrowPool, type(uint256).max);
}
}
}
_setupRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
}
/// @dev A modifier which checks that the caller has the admin role.
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "MultiRewardsBasePool: only admin");
_;
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, -(_amount.toInt256()));
}
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, _amount.toInt256());
}
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPointsForTransfer(reward, _from, _to, _value);
}
}
function rewardTokensLength() external view returns (uint256) {
return rewardTokens.length;
}
function addRewardToken(
address _reward,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration)
external onlyAdmin
{
require(_reward != address(0), "MultiRewardsBasePool.addRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.addRewardToken: Cannot escrow more than 100%");
if (!rewardTokensList[_reward]) {
rewardTokensList[_reward] = true;
rewardTokens.push(_reward);
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
if(_reward != address(0) && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
}
}
function updateRewardToken(address _reward, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration) external onlyAdmin {
require(rewardTokensList[_reward], "MultiRewardsBasePool.updateRewardToken: reward token not in the list");
require(_reward != address(0), "MultiRewardsBasePool.updateRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.updateRewardToken: Cannot escrow more than 100%");
if (escrowPools[_reward] != _escrowPool && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
}
function distributeRewards(address _reward, uint256 _amount) external override nonReentrant {
IERC20(_reward).safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_reward, _amount);
}
function claimRewards(address _reward, address _receiver) public {
uint256 rewardAmount = _prepareCollect(_reward, _msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortions[_reward] / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
ITimeLockPool escrowPool = ITimeLockPool(escrowPools[_reward]);
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDurations[_reward], _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
IERC20(_reward).safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_reward, _msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
function claimAll(address _receiver) external {
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
claimRewards(reward, _receiver);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractMultiRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractMultiRewards is IAbstractMultiRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed reward, address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
mapping(address => uint256) public pointsPerShare; //reward token address => points per share
mapping(address => mapping(address => int256)) public pointsCorrection; //reward token address => mapping(user address => pointsCorrection)
mapping(address => mapping(address => uint256)) public withdrawnRewards; //reward token address => mapping(user address => withdrawnRewards)
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _reward Address of the reward token
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _reward, address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_reward, _account) - withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _reward, address _account) public view override returns (uint256) {
return withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare[reward] * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _reward, address _account) public view override returns (uint256) {
return ((pointsPerShare[_reward] * getSharesOf(_account)).toInt256() + pointsCorrection[_reward][_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(address _reward, uint256 _amount) internal {
require(_reward != address(0), "AbstractRewards._distributeRewards: reward cannot be zero address");
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare[_reward] = pointsPerShare[_reward] + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _reward, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _reward, address _account) internal returns (uint256) {
require(_reward != address(0), "AbstractRewards._prepareCollect: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_reward, _account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_reward][_account] = withdrawnRewards[_reward][_account] + _withdrawableDividend;
emit RewardsWithdrawn(_reward, _account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _reward, address _from, address _to, uint256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPointsForTransfer: reward address cannot be zero address");
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: from address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: to address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare[_reward] * _shares).toInt256();
pointsCorrection[_reward][_from] = pointsCorrection[_reward][_from] + _magCorrection;
pointsCorrection[_reward][_to] = pointsCorrection[_reward][_to] - _magCorrection;
emit PointsCorrectionUpdated(_reward, _from, pointsCorrection[_reward][_from]);
emit PointsCorrectionUpdated(_reward, _to, pointsCorrection[_reward][_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare[reward]`.
*/
function _correctPoints(address _reward, address _account, int256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPoints: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_reward][_account] = pointsCorrection[_reward][_account] + (_shares * (pointsPerShare[_reward].toInt256()));
emit PointsCorrectionUpdated(_reward, _account, pointsCorrection[_reward][_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAbstractMultiRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param reward Address of the reward token
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param reward the address of the reward token
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, address indexed reward, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param reward the address of the reward token
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed reward, address indexed by, uint256 fundsWithdrawn);
} | Don't allow locking > maxLockDuration Enforce min lockup duration to prevent flash loan or MEV transaction ordering | function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
uint256 duration = _duration.min(maxLockDuration);
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
| 7,203 | [
1,
22293,
1404,
1699,
18887,
405,
943,
2531,
5326,
31716,
1131,
2176,
416,
3734,
358,
5309,
9563,
28183,
578,
7733,
58,
2492,
9543,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
8949,
16,
2254,
5034,
389,
8760,
16,
1758,
389,
24454,
13,
3903,
3849,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
24899,
24454,
480,
1758,
12,
20,
3631,
315,
950,
2531,
2864,
18,
323,
1724,
30,
5971,
2780,
506,
3634,
1758,
8863,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
950,
2531,
2864,
18,
323,
1724,
30,
2780,
443,
1724,
374,
8863,
203,
3639,
2254,
5034,
3734,
273,
389,
8760,
18,
1154,
12,
1896,
2531,
5326,
1769,
203,
3639,
3734,
273,
3734,
18,
1896,
12,
6236,
67,
6589,
67,
24951,
1769,
203,
203,
3639,
443,
1724,
1345,
18,
4626,
5912,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
443,
917,
1282,
951,
63,
67,
24454,
8009,
6206,
12,
758,
1724,
12590,
203,
5411,
3844,
30,
389,
8949,
16,
203,
5411,
787,
30,
2254,
1105,
12,
2629,
18,
5508,
3631,
203,
5411,
679,
30,
2254,
1105,
12,
2629,
18,
5508,
13,
397,
2254,
1105,
12,
8760,
13,
203,
3639,
289,
10019,
203,
203,
3639,
2254,
5034,
312,
474,
6275,
273,
389,
8949,
380,
31863,
5742,
12,
8760,
13,
342,
404,
73,
2643,
31,
203,
203,
3639,
389,
81,
474,
24899,
24454,
16,
312,
474,
6275,
1769,
203,
3639,
3626,
4019,
538,
16261,
24899,
8949,
16,
3734,
16,
389,
24454,
16,
389,
3576,
12021,
10663,
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
] |
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* @dev This simplifies the implementation of "user permissions".
*/
contract Whitelist is Pausable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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 conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale is Whitelist{
using SafeMath for uint256;
// The token being sold
MiniMeToken public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate = 6120;
// Amount of tokens sold
uint256 public tokensSold;
//Star of the crowdsale
uint256 startTime;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event buyx(address buyer, address contractAddr, uint256 amount);
constructor(address _wallet, MiniMeToken _token, uint256 starttime) public{
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
startTime = starttime;
}
function setCrowdsale(address _wallet, MiniMeToken _token, uint256 starttime) public{
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
startTime = starttime;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* fallback function ***DO NOT OVERRIDE***
*/
function () external whenNotPaused payable {
emit buyx(msg.sender, this, _getTokenAmount(msg.value));
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public whenNotPaused payable {
if ((tokensSold > 20884500000000000000000000 ) && (tokensSold <= 30791250000000000000000000)) {
rate = 5967;
}
else if ((tokensSold > 30791250000000000000000000) && (tokensSold <= 39270000000000000000000000)) {
rate = 5865;
}
else if ((tokensSold > 39270000000000000000000000) && (tokensSold <= 46856250000000000000000000)) {
rate = 5610;
}
else if ((tokensSold > 46856250000000000000000000) && (tokensSold <= 35700000000000000000000000)) {
rate = 5355;
}
else if (tokensSold > 35700000000000000000000000) {
rate = 5100;
}
uint256 weiAmount = msg.value;
uint256 tokens = _getTokenAmount(weiAmount);
tokensSold = tokensSold.add(tokens);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @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 {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract EmaCrowdSale is Crowdsale {
uint256 public hardcap;
uint256 public starttime;
Crowdsale public csale;
using SafeMath for uint256;
constructor(address wallet, MiniMeToken token, uint256 startTime, uint256 cap) Crowdsale(wallet, token, starttime) public onlyOwner
{
hardcap = cap;
starttime = startTime;
setCrowdsale(wallet, token, startTime);
}
function tranferPresaleTokens(address investor, uint256 ammount)public onlyOwner{
tokensSold = tokensSold.add(ammount);
token.transferFrom(this, investor, ammount);
}
function setTokenTransferState(bool state) public onlyOwner {
token.changeController(this);
token.enableTransfers(state);
}
function claim(address claimToken) public onlyOwner {
token.changeController(this);
token.claimTokens(claimToken);
}
function () external payable onlyWhitelisted whenNotPaused{
emit buyx(msg.sender, this, _getTokenAmount(msg.value));
buyTokens(msg.sender);
}
}
contract Controlled is Pausable {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; }
address public controller;
constructor() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyControllerorOwner {
controller = _newController;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled
{
using SafeMath for uint256;
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'V 1.0'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
constructor(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyControllerorOwner whenNotPaused returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount));
emit Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyControllerorOwner public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount));
updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount));
emit Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock)
return checkpoints[checkpoints.length.sub(1)].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length.sub(1);
while (max > min) {
uint mid = (max.add(min).add(1)).div(2);
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
/*require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/
revert();
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyControllerorOwner {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract EmaToken is MiniMeToken {
constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled)
MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public{
}
}
contract Configurator is Ownable {
EmaToken public token = EmaToken(0xC3EE57Fa8eD253E3F214048879977265967AE745);
EmaCrowdSale public crowdsale = EmaCrowdSale(0xAd97aF045F815d91621040809F863a5fb070B52d);
address ownerWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77;
address tokenfactory = 0xB74AA356913316ce49626527AE8543FFf23bB672;
address fundsWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77;
address incetivesPool = 0x95eac65414a6a650E2c71e3480AeEF0cF76392FA;
address FoundersAndTeam = 0x88C952c4A8fc156b883318CdA8b4a5279d989391;
address FuturePartners = 0x5B0333399E0D8F3eF1e5202b4eA4ffDdFD7a0382;
address Contributors = 0xa02dfB73de485Ebd9d37CbA4583e916F3bA94CeE;
address BountiesWal = 0xaB662f89A2c6e71BD8c7f754905cAaEC326BcdE7;
uint256 public crowdSaleStart;
function deploy() onlyOwner public{
owner = msg.sender;
// crowdsale.transferOwnership(ownerWallet);
// token.transferOwnership(ownerWallet);
// token.changeController(this);
token.generateTokens(crowdsale, 255000000000000000000000000); // Generate CrowdSale tokens
token.generateTokens(incetivesPool, 115000000000000000000000000); //generate Incentives pool tokens
token.generateTokens(FoundersAndTeam, 85000000000000000000000000); //generate Founders and team tokens
token.generateTokens(FuturePartners, 40000000000000000000000000); //generate future partners tokens and contributors
token.generateTokens(BountiesWal, 5000000000000000000000000); //generate contributors tokens
token.changeController(EmaCrowdSale(crowdsale));
token.transferOwnership(ownerWallet);
crowdsale.transferOwnership(ownerWallet);
}
} | `creationBlock` is the block number that the Clone Token was created | uint public creationBlock;
| 170,797 | [
1,
68,
17169,
1768,
68,
353,
326,
1203,
1300,
716,
326,
12758,
3155,
1703,
2522,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
540,
2254,
1071,
6710,
1768,
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
] |
./full_match/1/0xC4bfcAC43433C2435184c87aF26daDE9379b5B11/sources/project:/contracts/MtrollerUser.sol | * @notice Removes asset from sender's account liquidity calculation @dev Sender must not have an outstanding borrow balance in the asset, or be providing necessary collateral for an outstanding borrow. @param mToken The asset to be removed @return Whether or not the account successfully exited the market/ | function exitMarket(uint240 mToken) external returns (uint) {
return exitMarketInternal(mToken, msg.sender);
}
| 4,993,207 | [
1,
6220,
3310,
628,
5793,
1807,
2236,
4501,
372,
24237,
11096,
225,
15044,
1297,
486,
1240,
392,
20974,
29759,
11013,
316,
326,
3310,
16,
225,
578,
506,
17721,
4573,
4508,
2045,
287,
364,
392,
20974,
29759,
18,
225,
312,
1345,
1021,
3310,
358,
506,
3723,
327,
17403,
578,
486,
326,
2236,
4985,
21590,
326,
13667,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2427,
3882,
278,
12,
11890,
28784,
312,
1345,
13,
3903,
1135,
261,
11890,
13,
288,
203,
3639,
327,
2427,
3882,
278,
3061,
12,
81,
1345,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.2;
import "../Median.sol";
import "../vendor/SafeMath.sol";
import "./SafeMath128.sol";
import "./SafeMath64.sol";
import "./SafeMath32.sol";
import "../interfaces/LinkTokenInterface.sol";
import "../interfaces/WithdrawalInterface.sol";
import "./AggregatorInterface.sol";
import "../Owned.sol";
/**
* @title The Prepaid Aggregator contract
* @notice Node handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/
contract PrepaidAggregator is AggregatorInterface, Owned, WithdrawalInterface {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
RoundDetails details;
}
struct RoundDetails {
int256[] answers;
uint32 maxAnswers;
uint32 minAnswers;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestAnswer;
uint16 index;
}
uint128 public allocatedFunds;
uint128 public availableFunds;
// Round related params
uint128 public paymentAmount;
uint32 public maxAnswerCount;
uint32 public minAnswerCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public decimals;
bytes32 public description;
uint32 private reportingRoundId;
uint32 internal latestRoundId;
LinkTokenInterface private LINK;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
address[] private oracleAddresses;
event AvailableFundsUpdated(uint256 indexed amount);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minAnswerCount,
uint32 indexed maxAnswerCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OracleAdded(address indexed oracle);
event OracleRemoved(address indexed oracle);
event SubmissionReceived(
int256 indexed answer,
uint32 indexed round,
address indexed oracle
);
uint32 constant private ROUND_MAX = 2**32-1;
/**
* @notice Deploy with the address of the LINK token and initial payment amount
* @dev Sets the LinkToken address and amount of LINK paid
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per response
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
uint8 _decimals,
bytes32 _description
) public {
LINK = LinkTokenInterface(_link);
paymentAmount = _paymentAmount;
timeout = _timeout;
decimals = _decimals;
description = _description;
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _round is the ID of the round this answer pertains to
* @param _answer is the updated data that the oracle is submitting
*/
function updateAnswer(uint256 _round, int256 _answer)
external
onlyValidRoundId(uint32(_round))
onlyValidOracleRound(uint32(_round))
{
startNewRound(uint32(_round));
recordSubmission(_answer, uint32(_round));
updateRoundAnswer(uint32(_round));
payOracle(uint32(_round));
deleteRound(uint32(_round));
}
/**
* @notice called by the owner to add a new Oracle and update the round
* related parameters
* @param _oracle is the address of the new Oracle being added
* @param _minAnswers is the new minimum answer count for each round
* @param _maxAnswers is the new maximum answer count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function addOracle(
address _oracle,
uint32 _minAnswers,
uint32 _maxAnswers,
uint32 _restartDelay
)
external
onlyOwner()
onlyUnenabledAddress(_oracle)
{
require(oracleCount() < 42, "cannot add more than 42 oracles");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracleAddresses.push(_oracle);
oracles[_oracle].index = uint16(oracleAddresses.length.sub(1));
emit OracleAdded(_oracle);
updateFutureRounds(paymentAmount, _minAnswers, _maxAnswers, _restartDelay, timeout);
}
/**
* @notice called by the owner to remove an Oracle and update the round
* related parameters
* @param _oracle is the address of the Oracle being removed
* @param _minAnswers is the new minimum answer count for each round
* @param _maxAnswers is the new maximum answer count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function removeOracle(
address _oracle,
uint32 _minAnswers,
uint32 _maxAnswers,
uint32 _restartDelay
)
external
onlyOwner()
onlyEnabledAddress(_oracle)
{
oracles[_oracle].endingRound = reportingRoundId;
address tail = oracleAddresses[oracleCount().sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OracleRemoved(_oracle);
updateFutureRounds(paymentAmount, _minAnswers, _maxAnswers, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _newPaymentAmount is the payment amount for subsequent rounds
* @param _minAnswers is the new minimum answer count for each round
* @param _maxAnswers is the new maximum answer count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _newPaymentAmount,
uint32 _minAnswers,
uint32 _maxAnswers,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
onlyValidRange(_minAnswers, _maxAnswers, _restartDelay)
{
paymentAmount = _newPaymentAmount;
minAnswerCount = _minAnswers;
maxAnswerCount = _maxAnswers;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minAnswers,
_maxAnswers,
_restartDelay,
_timeout
);
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
uint128 pastAvailableFunds = availableFunds;
uint256 available = LINK.balanceOf(address(this)).sub(allocatedFunds);
availableFunds = uint128(available);
if (pastAvailableFunds != available) {
emit AvailableFundsUpdated(available);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint32) {
return uint32(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*/
function latestAnswer()
external
view
virtual
override
returns (int256)
{
return _latestAnswer();
}
/**
* @notice get the most recent updated at timestamp
*/
function latestTimestamp()
external
view
virtual
override
returns (uint256)
{
return _latestTimestamp();
}
/**
* @notice get the ID of the last updated round
*/
function latestRound()
external
view
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get the ID of the round most recently reported on
*/
function reportingRound()
external
view
returns (uint256)
{
return reportingRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*/
function getAnswer(uint256 _roundId)
external
view
virtual
override
returns (int256)
{
return _getAnswer(_roundId);
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*/
function getTimestamp(uint256 _roundId)
external
view
virtual
override
returns (uint256)
{
return _getTimestamp(_roundId);
}
/**
* @notice get the timed out status of a given round
* @param _roundId the round number to retrieve the timed out status for
*/
function getTimedOutStatus(uint256 _roundId)
external
view
returns (bool)
{
uint32 roundId = uint32(_roundId);
uint32 answeredIn = rounds[roundId].answeredInRound;
return answeredIn > 0 && answeredIn != roundId;
}
/**
* @notice get the start time of the current reporting round
*/
function reportingRoundStartedAt()
external
view
returns (uint256)
{
return rounds[reportingRoundId].startedAt;
}
/**
* @notice get the start time of a round
* @param _roundId the round number to retrieve the startedAt time for
*/
function getRoundStartedAt(uint256 _roundId)
external
view
returns (uint256)
{
return rounds[uint32(_roundId)].startedAt;
}
/**
* @notice get the round ID that an answer was originally reported in
* @param _roundId the round number to retrieve the answer for
*/
function getOriginatingRoundOfAnswer(uint256 _roundId)
external
view
returns (uint256)
{
return rounds[uint32(_roundId)].answeredInRound;
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawable()
external
view
override
returns (uint256)
{
return oracles[msg.sender].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdraw(address _recipient, uint256 _amount)
external
override
{
uint128 amount = uint128(_amount);
uint128 available = oracles[msg.sender].withdrawable;
require(available >= amount, "Insufficient balance");
oracles[msg.sender].withdrawable = available.sub(amount);
allocatedFunds = allocatedFunds.sub(amount);
assert(LINK.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
require(availableFunds >= _amount, "Insufficient funds");
require(LINK.transfer(_recipient, _amount), "LINK transfer failed");
updateAvailableFunds();
}
/**
* @notice get the latest submission for any oracle
* @param _oracle is the address to lookup the latest submission for
*/
function latestSubmission(address _oracle)
external
view
returns (int256, uint256)
{
return (oracles[_oracle].latestAnswer, oracles[_oracle].lastReportedRound);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transfered to the aggregator
*/
function onTokenTransfer(address, uint256, bytes memory) public {
updateAvailableFunds();
}
/**
* Internal
*/
/**
* @dev Internal implementation for latestAnswer
*/
function _latestAnswer()
internal
view
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @dev Internal implementation of latestTimestamp
*/
function _latestTimestamp()
internal
view
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @dev Internal implementation of getAnswer
*/
function _getAnswer(uint256 _roundId)
internal
view
returns (int256)
{
return rounds[uint32(_roundId)].answer;
}
/**
* @dev Internal implementation of getTimestamp
*/
function _getTimestamp(uint256 _roundId)
internal
view
returns (uint256)
{
return rounds[uint32(_roundId)].updatedAt;
}
/**
* Private
*/
function startNewRound(uint32 _id)
private
ifNewRound(_id)
ifDelayed(_id)
{
updateTimedOutRoundInfo(_id.sub(1));
reportingRoundId = _id;
rounds[_id].details.maxAnswers = maxAnswerCount;
rounds[_id].details.minAnswers = minAnswerCount;
rounds[_id].details.paymentAmount = paymentAmount;
rounds[_id].details.timeout = timeout;
rounds[_id].startedAt = uint64(block.timestamp);
oracles[msg.sender].lastStartedRound = _id;
emit NewRound(_id, msg.sender, rounds[_id].startedAt);
}
function updateTimedOutRoundInfo(uint32 _id)
private
ifTimedOut(_id)
onlyWithPreviousAnswer(_id)
{
uint32 prevId = _id.sub(1);
rounds[_id].answer = rounds[prevId].answer;
rounds[_id].answeredInRound = rounds[prevId].answeredInRound;
rounds[_id].updatedAt = uint64(block.timestamp);
delete rounds[_id].details;
}
function updateRoundAnswer(uint32 _id)
private
ifMinAnswersReceived(_id)
{
int256 newAnswer = Median.calculateInplace(rounds[_id].details.answers);
rounds[_id].answer = newAnswer;
rounds[_id].updatedAt = uint64(block.timestamp);
rounds[_id].answeredInRound = _id;
latestRoundId = _id;
emit AnswerUpdated(newAnswer, _id, now);
}
function payOracle(uint32 _id)
private
{
uint128 payment = rounds[_id].details.paymentAmount;
uint128 available = availableFunds.sub(payment);
availableFunds = available;
allocatedFunds = allocatedFunds.add(payment);
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(available);
}
function recordSubmission(int256 _answer, uint32 _id)
private
onlyWhenAcceptingAnswers(_id)
{
rounds[_id].details.answers.push(_answer);
oracles[msg.sender].lastReportedRound = _id;
oracles[msg.sender].latestAnswer = _answer;
emit SubmissionReceived(_answer, _id, msg.sender);
}
function deleteRound(uint32 _id)
private
ifMaxAnswersReceived(_id)
{
delete rounds[_id].details;
}
function timedOut(uint32 _id)
private
view
returns (bool)
{
uint64 startedAt = rounds[_id].startedAt;
uint32 roundTimeout = rounds[_id].details.timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function finished(uint32 _id)
private
view
returns (bool)
{
return rounds[_id].updatedAt > 0;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
/**
* Modifiers
*/
modifier onlyValidOracleRound(uint32 _id) {
uint32 startingRound = oracles[msg.sender].startingRound;
require(startingRound != 0, "Only updatable by whitelisted oracles");
require(startingRound <= _id, "New oracles cannot participate in in-progress rounds");
require(oracles[msg.sender].endingRound >= _id, "Oracle has been removed from whitelist");
require(oracles[msg.sender].lastReportedRound < _id, "Cannot update round reports");
_;
}
modifier ifMinAnswersReceived(uint32 _id) {
if (rounds[_id].details.answers.length >= rounds[_id].details.minAnswers) {
_;
}
}
modifier ifMaxAnswersReceived(uint32 _id) {
if (rounds[_id].details.answers.length == rounds[_id].details.maxAnswers) {
_;
}
}
modifier onlyWhenAcceptingAnswers(uint32 _id) {
require(rounds[_id].details.maxAnswers != 0, "Round not currently eligible for reporting");
_;
}
modifier ifNewRound(uint32 _id) {
if (_id == reportingRoundId.add(1)) {
_;
}
}
modifier ifDelayed(uint32 _id) {
uint256 lastStarted = oracles[msg.sender].lastStartedRound;
if (_id > lastStarted + restartDelay || lastStarted == 0) {
_;
}
}
modifier onlyValidRoundId(uint32 _id) {
require(_id == reportingRoundId || _id == reportingRoundId.add(1), "Must report on current round");
require(_id == 1 || finished(_id.sub(1)) || timedOut(_id.sub(1)), "Not eligible to bump round");
_;
}
modifier onlyValidRange(uint32 _min, uint32 _max, uint32 _restartDelay) {
uint32 oracleNum = oracleCount(); // Save on storage reads
require(oracleNum >= _max, "Cannot have the answer max higher oracle count");
require(_max >= _min, "Cannot have the answer minimum higher the max");
require(oracleNum == 0 || oracleNum > _restartDelay, "Restart delay must be less than oracle count");
_;
}
modifier onlyUnenabledAddress(address _oracle) {
require(oracles[_oracle].endingRound != ROUND_MAX, "Address is already recorded as an oracle");
_;
}
modifier onlyEnabledAddress(address _oracle) {
require(oracles[_oracle].endingRound == ROUND_MAX, "Address is not a whitelisted oracle");
_;
}
modifier ifTimedOut(uint32 _id) {
if (timedOut(_id)) {
_;
}
}
modifier onlyWithPreviousAnswer(uint32 _id) {
require(rounds[_id.sub(1)].updatedAt != 0, "Must have a previous answer to pull from");
_;
}
}
| * @notice get timestamp when an answer was last updated @param _roundId the round number to retrieve the updated timestamp for/ | function getTimestamp(uint256 _roundId)
external
view
virtual
override
returns (uint256)
{
return _getTimestamp(_roundId);
}
| 949,600 | [
1,
588,
2858,
1347,
392,
5803,
1703,
1142,
3526,
225,
389,
2260,
548,
326,
3643,
1300,
358,
4614,
326,
3526,
2858,
364,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
11940,
12,
11890,
5034,
389,
2260,
548,
13,
203,
565,
3903,
203,
565,
1476,
203,
565,
5024,
203,
565,
3849,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
327,
389,
588,
4921,
24899,
2260,
548,
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
] |
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*
* Subtraction and addition only here.
*/
library SafeMath {
/**
* @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;
}
}
/**
* @title A contract for generating unique identifiers for any requests.
* @dev Any contract that supports requesting inherits this contract to
* ensure request to be unique.
*/
contract RequestUid {
/**
* MEMBER: counter for request.
*/
uint256 public requestCount;
/**
* CONSTRUCTOR: initial counter with 0.
*/
constructor() public {
requestCount = 0;
}
/**
* METHOD: generate a new identifier.
* @dev 3 parameters as inputs:
* 1. blockhash of previous block;
* 2. the address of the initialized contract which is requested;
* 3. the value of counter.
* @return a 32-byte uid.
*/
function generateRequestUid() internal returns (bytes32 uid) {
return keccak256(abi.encodePacked(blockhash(block.number - uint256(1)), address(this), ++requestCount));
}
}
/**
* @dev This contract makes the inheritor have the functionality if the
* inheritor authorize the admin.
*/
contract AdminUpgradeable is RequestUid {
/**
* Event
* @dev After requesting of admin change, emit an event.
*/
event AdminChangeRequested(bytes32 _uid, address _msgSender, address _newAdmin);
/**
* Event
* @dev After confirming a request of admin change, emit an event.
*/
event AdminChangeConfirmed(bytes32 _uid, address _newAdmin);
/**
* STRUCT: A struct defined to store an request of admin change.
*/
struct AdminChangeRequest {
address newAdminAddress;
}
/**
* MEMBER: admin address(account address or contract address) which
* is authorize by the inheritor.
*/
address public admin;
/**
* MEMBER: a list of requests submitted.
*/
mapping (bytes32 => AdminChangeRequest) public adminChangeReqs;
/**
* MODIFIER: The operations from admin is allowed only.
*/
modifier adminOperations {
require(msg.sender == admin, "admin can call this method only");
_;
}
/**
* CONSTRUCTOR: Initialize with an admin address.
*/
constructor (address _admin) public RequestUid() {
admin = _admin;
}
/**
* METHOD: Upgrade the admin ---- request.
* @dev Request changing the admin address authorized.
* Anyone can call this method to submit a request to change
* the admin address. It will be pending until admin address
* comfirming the request, and the admin changes.
* @param _newAdmin The address of new admin, account or contract.
* @return uid The unique id of the request.
*/
function requestAdminChange(address _newAdmin) public returns (bytes32 uid) {
require(_newAdmin != address(0), "admin is not 0 address");
uid = generateRequestUid();
adminChangeReqs[uid] = AdminChangeRequest({
newAdminAddress: _newAdmin
});
emit AdminChangeRequested(uid, msg.sender, _newAdmin);
}
/**
* METHOD: Upgrade the admin ---- confirm.
* @dev Confirm a reqeust of admin change storing in the mapping
* of `adminChangeReqs`. The operation is authorized to the old
* admin only. The new admin will be authorized after the method
* called successfully.
* @param _uid The uid of request to change admin.
*/
function confirmAdminChange(bytes32 _uid) public adminOperations {
admin = getAdminChangeReq(_uid);
delete adminChangeReqs[_uid];
emit AdminChangeConfirmed(_uid, admin);
}
/**
* METHOD: Get the address of an admin request by uid.
* @dev It is a private method which gets address of an admin
* in the mapping `adminChangeReqs`
* @param _uid The uid of request to change admin.
* @return _newAdminAddress The address of new admin in the pending requests
*/
function getAdminChangeReq(bytes32 _uid) private view returns (address _newAdminAddress) {
AdminChangeRequest storage changeRequest = adminChangeReqs[_uid];
require(changeRequest.newAdminAddress != address(0));
return changeRequest.newAdminAddress;
}
}
/**
* @dev This is a contract which will be inherited by BICAProxy and BICALedger.
*/
contract BICALogicUpgradeable is AdminUpgradeable {
/**
* Event
* @dev After requesting of logic contract address change, emit an event.
*/
event LogicChangeRequested(bytes32 _uid, address _msgSender, address _newLogic);
/**
* Event
* @dev After confirming a request of logic contract address change, emit an event.
*/
event LogicChangeConfirmed(bytes32 _uid, address _newLogic);
/**
* STRUCT: A struct defined to store an request of Logic contract address change.
*/
struct LogicChangeRequest {
address newLogicAddress;
}
/**
* MEMBER: BICALogic address(a contract address) which implements logics of token.
*/
BICALogic public bicaLogic;
/**
* MEMBER: a list of requests of logic change submitted
*/
mapping (bytes32 => LogicChangeRequest) public logicChangeReqs;
/**
* MODIFIER: The call from bicaLogic is allowed only.
*/
modifier onlyLogic {
require(msg.sender == address(bicaLogic), "only logic contract is authorized");
_;
}
/**
* CONSTRUCTOR: Initialize with an admin address which is authorized to change
* the value of bicaLogic.
*/
constructor (address _admin) public AdminUpgradeable(_admin) {
bicaLogic = BICALogic(0x0);
}
/**
* METHOD: Upgrade the logic contract ---- request.
* @dev Request changing the logic contract address authorized.
* Anyone can call this method to submit a request to change
* the logic address. It will be pending until admin address
* comfirming the request, and the logic contract address changes, i.e.
* the value of bicaLogic changes.
* @param _newLogic The address of new logic contract.
* @return uid The unique id of the request.
*/
function requestLogicChange(address _newLogic) public returns (bytes32 uid) {
require(_newLogic != address(0), "new logic address can not be 0");
uid = generateRequestUid();
logicChangeReqs[uid] = LogicChangeRequest({
newLogicAddress: _newLogic
});
emit LogicChangeRequested(uid, msg.sender, _newLogic);
}
/**
* METHOD: Upgrade the logic contract ---- confirm.
* @dev Confirm a reqeust of logic contract change storing in the
* mapping of `logicChangeReqs`. The operation is authorized to
* the admin only.
* @param _uid The uid of request to change logic contract.
*/
function confirmLogicChange(bytes32 _uid) public adminOperations {
bicaLogic = getLogicChangeReq(_uid);
delete logicChangeReqs[_uid];
emit LogicChangeConfirmed(_uid, address(bicaLogic));
}
/**
* METHOD: Get the address of an logic contract address request by uid.
* @dev It is a private method which gets address of an address
* in the mapping `adminChangeReqs`
* @param _uid The uid of request to change logic contract address.
* @return _newLogicAddress The address of new logic contract address
* in the pending requests
*/
function getLogicChangeReq(bytes32 _uid) private view returns (BICALogic _newLogicAddress) {
LogicChangeRequest storage changeRequest = logicChangeReqs[_uid];
require(changeRequest.newLogicAddress != address(0));
return BICALogic(changeRequest.newLogicAddress);
}
}
/**
* @dev This contract is the core contract of all logic. It links `bicaProxy`
* and `bicaLedger`. It implements the issue of new amount of token, burn some
* value of someone's token.
*/
contract BICALogic is AdminUpgradeable {
using SafeMath for uint256;
/**
* Event
* @dev After issuing an ammout of BICA, emit an event for the value of requester.
*/
event Requester(address _supplyAddress, address _receiver, uint256 _valueRequested);
/**
* Event
* @dev After issuing an ammout of BICA, emit an event of paying margin.
*/
event PayMargin(address _supplyAddress, address _marginAddress, uint256 _marginValue);
/**
* Event
* @dev After issuing an ammout of BICA, emit an event of paying interest.
*/
event PayInterest(address _supplyAddress, address _interestAddress, uint256 _interestValue);
/**
* Event
* @dev After issuing an ammout of BICA, emit an event of paying multi fee.
*/
event PayMultiFee(address _supplyAddress, address _feeAddress, uint256 _feeValue);
/**
* Event
* @dev After freezing a user address, emit an event in logic contract.
*/
event AddressFrozenInLogic(address indexed addr);
/**
* Event
* @dev After unfreezing a user address, emit an event in logic contract.
*/
event AddressUnfrozenInLogic(address indexed addr);
/**
* MEMBER: A reference to the proxy contract.
* It links the proxy contract in one direction.
*/
BICAProxy public bicaProxy;
/**
* MEMBER: A reference to the ledger contract.
* It links the ledger contract in one direction.
*/
BICALedger public bicaLedger;
/**
* MODIFIER: The call from bicaProxy is allowed only.
*/
modifier onlyProxy {
require(msg.sender == address(bicaProxy), "only the proxy contract allowed only");
_;
}
/**
* CONSTRUCTOR: Initialize with the proxy contract address, the ledger
* contract and an admin address.
*/
constructor (address _bicaProxy, address _bicaLedger, address _admin) public AdminUpgradeable(_admin) {
bicaProxy = BICAProxy(_bicaProxy);
bicaLedger = BICALedger(_bicaLedger);
}
/**
* METHOD: `approve` operation in logic contract.
* @dev Receive the call request of `approve` from proxy contract and
* request approve operation to ledger contract. Need to check the sender
* and spender are not frozen
* @param _sender The address initiating the approval in proxy.
* @return success or not.
*/
function approveWithSender(address _sender, address _spender, uint256 _value) public onlyProxy returns (bool success){
require(_spender != address(0));
bool senderFrozen = bicaLedger.getFrozenByAddress(_sender);
require(!senderFrozen, "Sender is frozen");
bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender);
require(!spenderFrozen, "Spender is frozen");
bicaLedger.setAllowance(_sender, _spender, _value);
bicaProxy.emitApproval(_sender, _spender, _value);
return true;
}
/**
* METHOD: Core logic of the `increaseApproval` method in proxy contract.
* @dev Receive the call request of `increaseApproval` from proxy contract
* and request increasing value of allownce to ledger contract. Need to
* check the sender
* and spender are not frozen
* @param _sender The address initiating the approval in proxy.
* @return success or not.
*/
function increaseApprovalWithSender(address _sender, address _spender, uint256 _addedValue) public onlyProxy returns (bool success) {
require(_spender != address(0));
bool senderFrozen = bicaLedger.getFrozenByAddress(_sender);
require(!senderFrozen, "Sender is frozen");
bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender);
require(!spenderFrozen, "Spender is frozen");
uint256 currentAllowance = bicaLedger.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance.add(_addedValue);
require(newAllowance >= currentAllowance);
bicaLedger.setAllowance(_sender, _spender, newAllowance);
bicaProxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/**
* METHOD: Core logic of the `decreaseApproval` method in proxy contract.
* @dev Receive the call request of `decreaseApproval` from proxy contract
* and request decreasing value of allownce to ledger contract. Need to
* check the sender and spender are not frozen
* @param _sender The address initiating the approval in proxy.
* @return success or not.
*/
function decreaseApprovalWithSender(address _sender, address _spender, uint256 _subtractedValue) public onlyProxy returns (bool success) {
require(_spender != address(0));
bool senderFrozen = bicaLedger.getFrozenByAddress(_sender);
require(!senderFrozen, "Sender is frozen");
bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender);
require(!spenderFrozen, "Spender is frozen");
uint256 currentAllowance = bicaLedger.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance.sub(_subtractedValue);
require(newAllowance <= currentAllowance);
bicaLedger.setAllowance(_sender, _spender, newAllowance);
bicaProxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/**
* METHOD: Core logic of comfirming request of issuetoken to a specified receiver.
* @dev Admin can issue an ammout of BICA only.
* @param _requesterAccount The address of request account.
* @param _requestValue The value of requester.
* @param _marginAccount The address of margin account.
* @param _marginValue The value of token to pay to margin account.
* @param _interestAccount The address accepting interest.
* @param _interestValue The value of interest.
* @param _otherFeeAddress The address accepting multi fees.
* @param _otherFeeValue The value of other fees.
*/
function issue(address _requesterAccount, uint256 _requestValue,
address _marginAccount, uint256 _marginValue,
address _interestAccount, uint256 _interestValue,
address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations {
require(_requesterAccount != address(0));
require(_marginAccount != address(0));
require(_interestAccount != address(0));
require(_otherFeeAddress != address(0));
require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen");
require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen");
require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen");
require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen");
uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue);
uint256 supply = bicaLedger.totalSupply();
uint256 newSupply = supply.add(requestTotalValue);
if (newSupply >= supply) {
bicaLedger.setTotalSupply(newSupply);
bicaLedger.addBalance(_marginAccount, _marginValue);
bicaLedger.addBalance(_interestAccount, _interestValue);
if ( _otherFeeValue > 0 ){
bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue);
}
bicaLedger.addBalance(_requesterAccount, _requestValue);
emit Requester(msg.sender, _requesterAccount, _requestValue);
emit PayMargin(msg.sender, _marginAccount, _marginValue);
emit PayInterest(msg.sender, _interestAccount, _interestValue);
emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue);
bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue);
bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue);
bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue);
bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue);
}
}
/**
* METHOD: Burn the specified value of the message sender's balance.
* @dev Admin can call this method to burn some amount of BICA.
* @param _value The amount of token to be burned.
* @return success or not.
*/
function burn(uint256 _value) public adminOperations returns (bool success) {
bool burnerFrozen = bicaLedger.getFrozenByAddress(msg.sender);
require(!burnerFrozen, "Burner is frozen");
uint256 balanceOfSender = bicaLedger.balances(msg.sender);
require(_value <= balanceOfSender);
bicaLedger.setBalance(msg.sender, balanceOfSender.sub(_value));
bicaLedger.setTotalSupply(bicaLedger.totalSupply().sub(_value));
bicaProxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/**
* METHOD: Freeze a user address.
* @dev Admin can call this method to freeze a user account.
* @param _user user address.
*/
function freeze(address _user) public adminOperations {
require(_user != address(0), "the address to be frozen cannot be 0");
bicaLedger.freezeByAddress(_user);
emit AddressFrozenInLogic(_user);
}
/**
* METHOD: Unfreeze a user address.
* @dev Admin can call this method to unfreeze a user account.
* @param _user user address.
*/
function unfreeze(address _user) public adminOperations {
require(_user != address(0), "the address to be unfrozen cannot be 0");
bicaLedger.unfreezeByAddress(_user);
emit AddressUnfrozenInLogic(_user);
}
/**
* METHOD: Core logic of `transferFrom` interface method in ERC20 token standard.
* @dev It can only be called by the `bicaProxy` contract.
* @param _sender The address initiating the approval in proxy.
* @return success or not.
*/
function transferFromWithSender(address _sender, address _from, address _to, uint256 _value) public onlyProxy returns (bool success){
require(_to != address(0));
bool senderFrozen = bicaLedger.getFrozenByAddress(_sender);
require(!senderFrozen, "Sender is frozen");
bool fromFrozen = bicaLedger.getFrozenByAddress(_from);
require(!fromFrozen, "`from` is frozen");
bool toFrozen = bicaLedger.getFrozenByAddress(_to);
require(!toFrozen, "`to` is frozen");
uint256 balanceOfFrom = bicaLedger.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = bicaLedger.allowed(_from, _sender);
require(_value <= senderAllowance);
bicaLedger.setBalance(_from, balanceOfFrom.sub(_value));
bicaLedger.addBalance(_to, _value);
bicaLedger.setAllowance(_from, _sender, senderAllowance.sub(_value));
bicaProxy.emitTransfer(_from, _to, _value);
return true;
}
/**
* METHOD: Core logic of `transfer` interface method in ERC20 token standard.
* @dev It can only be called by the `bicaProxy` contract.
* @param _sender The address initiating the approval in proxy.
* @return success or not.
*/
function transferWithSender(address _sender, address _to, uint256 _value) public onlyProxy returns (bool success){
require(_to != address(0));
bool senderFrozen = bicaLedger.getFrozenByAddress(_sender);
require(!senderFrozen, "sender is frozen");
bool toFrozen = bicaLedger.getFrozenByAddress(_to);
require(!toFrozen, "to is frozen");
uint256 balanceOfSender = bicaLedger.balances(_sender);
require(_value <= balanceOfSender);
bicaLedger.setBalance(_sender, balanceOfSender.sub(_value));
bicaLedger.addBalance(_to, _value);
bicaProxy.emitTransfer(_sender, _to, _value);
return true;
}
/**
* METHOD: Core logic of `totalSupply` interface method in ERC20 token standard.
*/
function totalSupply() public view returns (uint256) {
return bicaLedger.totalSupply();
}
/**
* METHOD: Core logic of `balanceOf` interface method in ERC20 token standard.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return bicaLedger.balances(_owner);
}
/**
* METHOD: Core logic of `allowance` interface method in ERC20 token standard.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return bicaLedger.allowed(_owner, _spender);
}
}
/**
* @dev This contract is the core storage contract of ERC20 token ledger.
* It defines some operations of data in the storage.
*/
contract BICALedger is BICALogicUpgradeable {
using SafeMath for uint256;
/**
* MEMBER: The total supply of the token.
*/
uint256 public totalSupply;
/**
* MEMBER: The mapping of balance of users.
*/
mapping (address => uint256) public balances;
/**
* MEMBER: The mapping of allowance of users.
*/
mapping (address => mapping (address => uint256)) public allowed;
/**
* MEMBER: The mapping of frozen addresses.
*/
mapping(address => bool) public frozen;
/**
* Event
* @dev After freezing a user address, emit an event in ledger contract.
*/
event AddressFrozen(address indexed addr);
/**
* Event
* @dev After unfreezing a user address, emit an event in ledger contract.
*/
event AddressUnfrozen(address indexed addr);
/**
* CONSTRUCTOR: Initialize with an admin address.
*/
constructor (address _admin) public BICALogicUpgradeable(_admin) {
totalSupply = 0;
}
/**
* METHOD: Check an address is frozen or not.
* @dev check an address is frozen or not. It can be call by logic contract only.
* @param _user user addree.
*/
function getFrozenByAddress(address _user) public view onlyLogic returns (bool frozenOrNot) {
// frozenOrNot = false;
return frozen[_user];
}
/**
* METHOD: Freeze an address.
* @dev Freeze an address. It can be called by logic contract only.
* @param _user user addree.
*/
function freezeByAddress(address _user) public onlyLogic {
require(!frozen[_user], "user already frozen");
frozen[_user] = true;
emit AddressFrozen(_user);
}
/**
* METHOD: Unfreeze an address.
* @dev Unfreeze an address. It can be called by logic contract only.
* @param _user user addree.
*/
function unfreezeByAddress(address _user) public onlyLogic {
require(frozen[_user], "address already unfrozen");
frozen[_user] = false;
emit AddressUnfrozen(_user);
}
/**
* METHOD: Set `totalSupply` in the ledger contract.
* @dev It will be called when a new issue is confirmed. It can be called
* by logic contract only.
* @param _newTotalSupply The value of new total supply.
*/
function setTotalSupply(uint256 _newTotalSupply) public onlyLogic {
totalSupply = _newTotalSupply;
}
/**
* METHOD: Set allowance for owner to a spender in the ledger contract.
* @dev It will be called when the owner modify the allowance to the
* spender. It can be called by logic contract only.
* @param _owner The address allow spender to spend.
* @param _spender The address allowed to spend.
* @param _value The limit of how much can be spent by `_spender`.
*/
function setAllowance(address _owner, address _spender, uint256 _value) public onlyLogic {
allowed[_owner][_spender] = _value;
}
/**
* METHOD: Set balance of the owner in the ledger contract.
* @dev It will be called when the owner modify the balance of owner
* in logic. It can be called by logic contract only.
* @param _owner The address who owns the balance.
* @param _newBalance The balance to be set.
*/
function setBalance(address _owner, uint256 _newBalance) public onlyLogic {
balances[_owner] = _newBalance;
}
/**
* METHOD: Add balance of the owner in the ledger contract.
* @dev It will be called when the balance of owner increases.
* It can be called by logic contract only.
* @param _owner The address who owns the balance.
* @param _balanceIncrease The balance to be add.
*/
function addBalance(address _owner, uint256 _balanceIncrease) public onlyLogic {
balances[_owner] = balances[_owner].add(_balanceIncrease);
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view 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 view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @dev This contract is a viewer of ERC20 token standard.
* It includes no logic and data.
*/
contract BICAProxy is ERC20Interface, BICALogicUpgradeable {
/**
* MEMBER: The name of the token.
*/
string public name;
/**
* MEMBER: The symbol of the token.
*/
string public symbol;
/**
* MEMBER: The number of decimals of the token.
*/
uint public decimals;
/**
* CONSTRUCTOR: Initialize with an admin address.
*/
constructor (address _admin) public BICALogicUpgradeable(_admin){
name = "BitCapital Coin";
symbol = 'BICA';
decimals = 2;
}
/**
* METHOD: Get `totalSupply` of token.
* @dev It is the standard method of ERC20.
* @return The total token supply.
*/
function totalSupply() public view returns (uint256) {
return bicaLogic.totalSupply();
}
/**
* METHOD: Get the balance of a owner.
* @dev It is the standard method of ERC20.
* @return The balance of a owner.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return bicaLogic.balanceOf(_owner);
}
/**
* METHOD: Emit a Transfer event in proxy contract.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic {
emit Transfer(_from, _to, _value);
}
/**
* METHOD: The message sender sends some amount of token to receiver.
* @dev It will call the logic contract to send some token to receiver.
* It is the standard method of ERC20.
* @return success or not
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return bicaLogic.transferWithSender(msg.sender, _to, _value);
}
/**
* METHOD: Transfer amount of tokens from `_from` to `_to`.
* @dev It is the standard method of ERC20.
* @return success or not
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value);
}
/**
* METHOD: Emit a Approval event in proxy contract.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic {
emit Approval(_owner, _spender, _value);
}
/**
* METHOD: Allow `_spender` to be able to spend `_value` token.
* @dev It is the standard method of ERC20.
* @return success or not
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
return bicaLogic.approveWithSender(msg.sender, _spender, _value);
}
/**
* METHOD: Increase allowance value of message sender to `_spender`.
* @return success or not
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/**
* METHOD: Decrease allowance value of message sender to `_spender`.
* @return success or not
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/**
* METHOD: Return the allowance value of `_owner` to `_spender`.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return bicaLogic.allowance(_owner, _spender);
}
} | * @dev This contract is a viewer of ERC20 token standard. It includes no logic and data./ | contract BICAProxy is ERC20Interface, BICALogicUpgradeable {
string public name;
string public symbol;
uint public decimals;
constructor (address _admin) public BICALogicUpgradeable(_admin){
name = "BitCapital Coin";
symbol = 'BICA';
decimals = 2;
}
function totalSupply() public view returns (uint256) {
return bicaLogic.totalSupply();
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return bicaLogic.balanceOf(_owner);
}
function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic {
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
return bicaLogic.transferWithSender(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value);
}
function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic {
emit Approval(_owner, _spender, _value);
}
function approve(address _spender, uint256 _value) public returns (bool success) {
return bicaLogic.approveWithSender(msg.sender, _spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return bicaLogic.allowance(_owner, _spender);
}
} | 2,479,145 | [
1,
2503,
6835,
353,
279,
14157,
434,
4232,
39,
3462,
1147,
4529,
18,
2597,
6104,
1158,
4058,
471,
501,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
605,
2871,
37,
3886,
353,
4232,
39,
3462,
1358,
16,
605,
10109,
717,
335,
10784,
429,
288,
203,
203,
565,
533,
1071,
508,
31,
203,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
2254,
1071,
15105,
31,
203,
203,
565,
3885,
261,
2867,
389,
3666,
13,
1071,
605,
10109,
717,
335,
10784,
429,
24899,
3666,
15329,
203,
3639,
508,
273,
315,
5775,
4664,
7053,
28932,
14432,
203,
3639,
3273,
273,
296,
38,
2871,
37,
13506,
203,
3639,
15105,
273,
576,
31,
203,
565,
289,
203,
377,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
324,
26433,
20556,
18,
4963,
3088,
1283,
5621,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
3639,
327,
324,
26433,
20556,
18,
12296,
951,
24899,
8443,
1769,
203,
565,
289,
203,
203,
565,
445,
3626,
5912,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1338,
20556,
288,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
327,
324,
26433,
20556,
18,
13866,
1190,
12021,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
2
] |
./partial_match/1/0xe9A8E0D074fF327BC0466a4C9f33A64C17A0902D/sources/contracts/arbitrage/BancorArbitrage.sol | * @dev returns the min bnt burn amount note: deprecated/ | function minBurn() external pure returns (uint256) {
return 0;
}
| 9,181,313 | [
1,
6154,
326,
1131,
324,
496,
18305,
3844,
4721,
30,
6849,
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,
1131,
38,
321,
1435,
3903,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x5b986aeC092Ed36d0d93ebCEd75c89b2Ceeb393B/sources/NewGame.sol | * @dev function to handle ethereum sent directly to contract address./ | function fallback() external payable{
require(msg.value > 0 , "Transaction amount must be more than 0");
buy(0x0000000000000000000000000000000000000000, msg.value, 0x0000000000000000000000000000000000000000);
}
| 5,112,345 | [
1,
915,
358,
1640,
13750,
822,
379,
3271,
5122,
358,
6835,
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,
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,
5922,
1435,
3903,
8843,
429,
95,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
269,
315,
3342,
3844,
1297,
506,
1898,
2353,
374,
8863,
203,
3639,
30143,
12,
20,
92,
12648,
12648,
12648,
12648,
12648,
16,
1234,
18,
1132,
16,
374,
92,
12648,
12648,
12648,
12648,
12648,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* ██████╗ ███████╗████████╗███████╗ ██████╗ ███╗ ██╗ █████╗ ██╗
* ██╔══██╗ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗ ████╗ ██║ ██╔══██╗ ██║
* ██████╔╝ █████╗ ██║ █████╗ ██████╔╝ ██╔██╗ ██║ ███████║ ██║
* ██╔══██╗ ██╔══╝ ██║ ██╔══╝ ██╔══██╗ ██║╚██╗██║ ██╔══██║ ██║
* ██║ ██║ ███████╗ ██║ ███████╗ ██║ ██║ ██║ ╚████║ ██║ ██║ ███████╗
* ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝
*
* Contacts:
*
* -- t.me/Reternal
* -- https://www.reternal.net
*
* - GAIN PER 24 HOURS:
*
* -- Individual balance < 1 Ether: 3.15%
* -- Individual balance >= 1 Ether: 3.25%
* -- Individual balance >= 4 Ether: 3.45%
* -- Individual balance >= 12 Ether: 3.65%
* -- Individual balance >= 50 Ether: 3.85%
* -- Individual balance >= 200 Ether: 4.15%
*
* -- Contract balance < 500 Ether: 0%
* -- Contract balance >= 500 Ether: 0.10%
* -- Contract balance >= 1500 Ether: 0.20%
* -- Contract balance >= 2500 Ether: 0.30%
* -- Contract balance >= 7000 Ether: 0.45%
* -- Contract balance >= 15000 Ether: 0.65%
*
* - Minimal contribution 0.01 eth
* - Contribution allocation schemes:
* -- 95% payments
* -- 5% Marketing + Operating Expenses
*
* - How to use:
* 1. Send from your personal ETH wallet to the smart-contract address any amount more than or equal to 0.01 ETH
* 2. Add your refferer's wallet to a HEX data in your transaction to
* get a bonus amount back to your wallet only for the FIRST deposit
* IMPORTANT: if you want to support Reternal project, you can leave your HEX data field empty,
* if you have no referrer and do not want to support Reternal, you can type 'noreferrer'
* if there is no referrer, you will not get any bonuses
* 3. Use etherscan.io to verify your transaction
* 4. Claim your dividents by sending 0 ether transaction (available anytime)
* 5. You can reinvest anytime you want
*
* RECOMMENDED GAS LIMIT: 200000
* RECOMMENDED GAS PRICE: https://ethgasstation.info/
*
* The smart-contract has a "restart" function, more info at www.reternal.net
*
* If you want to check your dividents, you can use etherscan.io site, following the "Internal Txns" tab of your wallet
* WARNING: do not use exchanges' wallets - you will loose your funds. Only use your personal wallet for transactions
*
*/
contract Reternal {
// Investor's data storage
mapping (address => Investor) public investors;
address[] public addresses;
struct Investor
{
uint id;
uint deposit;
uint depositCount;
uint block;
address referrer;
}
uint constant public MINIMUM_INVEST = 10000000000000000 wei;
address defaultReferrer = 0x25EDFd665C2898c2898E499Abd8428BaC616a0ED;
uint public round;
uint public totalDepositAmount;
bool public pause;
uint public restartBlock;
bool ref_flag;
// Investors' dividents increase goals due to a bank growth
uint bank1 = 5e20; // 500 eth
uint bank2 = 15e20; // 1500 eth
uint bank3 = 25e20; // 2500 eth
uint bank4 = 7e21; // 7000 eth
uint bank5 = 15e20; // 15000 eth
// Investors' dividents increase due to individual deposit amount
uint dep1 = 1e18; // 1 ETH
uint dep2 = 4e18; // 4 ETH
uint dep3 = 12e18; // 12 ETH
uint dep4 = 5e19; // 50 ETH
uint dep5 = 2e20; // 200 ETH
event NewInvestor(address indexed investor, uint deposit, address referrer);
event PayOffDividends(address indexed investor, uint value);
event refPayout(address indexed investor, uint value, address referrer);
event NewDeposit(address indexed investor, uint value);
event NextRoundStarted(uint round, uint block, address addr, uint value);
constructor() public {
addresses.length = 1;
round = 1;
pause = false;
}
function restart() private {
address addr;
for (uint i = addresses.length - 1; i > 0; i--) {
addr = addresses[i];
addresses.length -= 1;
delete investors[addr];
}
emit NextRoundStarted(round, block.number, msg.sender, msg.value);
pause = false;
round += 1;
totalDepositAmount = 0;
createDeposit();
}
function getRaisedPercents(address addr) internal view returns(uint){
// Individual deposit percentage sums up with 'Reternal total fund' percentage
uint percent = getIndividualPercent() + getBankPercent();
uint256 amount = investors[addr].deposit * percent / 100*(block.number-investors[addr].block)/6000;
return(amount / 100);
}
function payDividends() private{
require(investors[msg.sender].id > 0, "Investor not found.");
// Investor's total raised amount
uint amount = getRaisedPercents(msg.sender);
if (address(this).balance < amount) {
pause = true;
restartBlock = block.number + 6000;
return;
}
// Service fee deduction
uint FeeToWithdraw = amount * 5 / 100;
uint payment = amount - FeeToWithdraw;
address(0xD9bE11E7412584368546b1CaE64b6C384AE85ebB).transfer(FeeToWithdraw);
msg.sender.transfer(payment);
emit PayOffDividends(msg.sender, amount);
}
function createDeposit() private{
Investor storage user = investors[msg.sender];
if (user.id == 0) {
// Check for malicious smart-contract
msg.sender.transfer(0 wei);
user.id = addresses.push(msg.sender);
if (msg.data.length != 0) {
address referrer = bytesToAddress(msg.data);
// Check for referrer's registration. Check for self referring
if (investors[referrer].id > 0 && referrer != msg.sender) {
user.referrer = referrer;
// Cashback only for the first deposit
if (user.depositCount == 0) { // cashback only for the first deposit
uint cashback = msg.value / 100;
if (msg.sender.send(cashback)) {
emit refPayout(msg.sender, cashback, referrer);
}
}
}
} else {
// If data is empty:
user.referrer = defaultReferrer;
}
emit NewInvestor(msg.sender, msg.value, referrer);
} else {
// Dividents payment for an investor
payDividends();
}
// 2% from a referral deposit transfer to a referrer
uint payReferrer = msg.value * 2 / 100; // 2% from referral deposit to referrer
//
if (user.referrer == defaultReferrer) {
user.referrer.transfer(payReferrer);
} else {
investors[referrer].deposit += payReferrer;
}
user.depositCount++;
user.deposit += msg.value;
user.block = block.number;
totalDepositAmount += msg.value;
emit NewDeposit(msg.sender, msg.value);
}
function() external payable {
if(pause) {
if (restartBlock <= block.number) { restart(); }
require(!pause, "Eternal is restarting, wait for the block in restartBlock");
} else {
if (msg.value == 0) {
payDividends();
return;
}
require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether");
createDeposit();
}
}
function getBankPercent() public view returns(uint){
uint contractBalance = address(this).balance;
uint totalBank1 = bank1;
uint totalBank2 = bank2;
uint totalBank3 = bank3;
uint totalBank4 = bank4;
uint totalBank5 = bank5;
if(contractBalance < totalBank1){
return(0); // If bank lower than 500, whole procent doesnt add
}
if(contractBalance >= totalBank1 && contractBalance < totalBank2){
return(10); // If bank amount more than or equal to 500 ETH, whole procent add 0.10%
}
if(contractBalance >= totalBank2 && contractBalance < totalBank3){
return(20); // If bank amount more than or equal to 1500 ETH, whole procent add 0.10%
}
if(contractBalance >= totalBank3 && contractBalance < totalBank4){
return(30); // If bank amount more than or equal to 2500 ETH, whole procent add 0.10%
}
if(contractBalance >= totalBank4 && contractBalance < totalBank5){
return(45); // If bank amount more than or equal to 7000 ETH, whole procent add 0.15%
}
if(contractBalance >= totalBank5){
return(65); // If bank amount more than or equal to 15000 ETH, whole procent add 0.20%
}
}
function getIndividualPercent() public view returns(uint){
uint userBalance = investors[msg.sender].deposit;
uint totalDeposit1 = dep1;
uint totalDeposit2 = dep2;
uint totalDeposit3 = dep3;
uint totalDeposit4 = dep4;
uint totalDeposit5 = dep5;
if(userBalance < totalDeposit1){
return(315); // 3.15% by default, investor deposit lower than 1 ETH
}
if(userBalance >= totalDeposit1 && userBalance < totalDeposit2){
return(325); // 3.25% Your Deposit more than or equal to 1 ETH
}
if(userBalance >= totalDeposit2 && userBalance < totalDeposit3){
return(345); // 3.45% Your Deposit more than or equal to 4 ETH
}
if(userBalance >= totalDeposit3 && userBalance < totalDeposit4){
return(360); // 3.60% Your Deposit more than or equal to 12 ETH
}
if(userBalance >= totalDeposit4 && userBalance < totalDeposit5){
return(385); // 3.85% Your Deposit more than or equal to 50 ETH
}
if(userBalance >= totalDeposit5){
return(415); // 4.15% Your Deposit more than or equal to 200 ETH
}
}
function getInvestorCount() public view returns (uint) {
return addresses.length - 1;
}
function bytesToAddress(bytes bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
} | 3.85% Your Deposit more than or equal to 50 ETH
| return(385); | 7,872,708 | [
1,
23,
18,
7140,
9,
20471,
4019,
538,
305,
1898,
2353,
578,
3959,
358,
6437,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
327,
12,
23,
7140,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xB149A66dd8118490857d9d42f2cA01bB3b736407/sources/project_/contracts/Coin.sol | * @dev Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./ | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
| 1,850,574 | [
1,
3641,
6478,
23850,
3304,
326,
1699,
1359,
17578,
358,
1375,
87,
1302,
264,
68,
635,
326,
4894,
18,
1220,
353,
392,
10355,
358,
288,
12908,
537,
97,
716,
848,
506,
1399,
487,
279,
20310,
360,
367,
364,
9688,
11893,
316,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
1297,
1240,
1699,
1359,
364,
326,
4894,
434,
622,
4520,
1375,
1717,
1575,
329,
620,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
1071,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
1758,
3410,
273,
389,
3576,
12021,
5621,
203,
3639,
2254,
5034,
783,
7009,
1359,
273,
1699,
1359,
12,
8443,
16,
17571,
264,
1769,
203,
3639,
2583,
12,
2972,
7009,
1359,
1545,
10418,
329,
620,
16,
315,
654,
39,
3462,
30,
23850,
8905,
1699,
1359,
5712,
3634,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
12908,
537,
12,
8443,
16,
17571,
264,
16,
783,
7009,
1359,
300,
10418,
329,
620,
1769,
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
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IBaseFee
interface IBaseFee {
function basefee_global() external view returns (uint256);
}
// Part: IConvexDeposit
interface IConvexDeposit {
// deposit into convex, receive a tokenized deposit. parameter to stake immediately (we always do this).
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
// burn a tokenized deposit (Convex deposit tokens) to receive curve lp tokens back
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
// give us info about a pool based on its pid
function poolInfo(uint256)
external
view
returns (
address,
address,
address,
address,
address,
bool
);
}
// Part: IConvexRewards
interface IConvexRewards {
// strategy's staked balance in the synthetix staking contract
function balanceOf(address account) external view returns (uint256);
// read how much claimable CRV a strategy has
function earned(address account) external view returns (uint256);
// stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
// withdraw to a convex tokenized deposit, probably never need to use this
function withdraw(uint256 _amount, bool _claim) external returns (bool);
// withdraw directly to curve LP token, this is what we primarily use
function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
// claim rewards, with an option to claim extra rewards or not
function getReward(address _account, bool _claimExtras)
external
returns (bool);
// check if we have rewards on a pool
function extraRewardsLength() external view returns (uint256);
// if we have rewards, see what the address is
function extraRewards(uint256 _reward) external view returns (address);
// read our rewards token
function rewardToken() external view returns (address);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IUniswapV2Router02
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;
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: StrategyConvexBase
abstract contract StrategyConvexBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// convex stuff
address public constant depositContract =
0xF403C135812408BFbE8713b5A23a04b3D48AAE31; // this is the deposit contract that all pools use, aka booster
address public rewardsContract; // This is unique to each curve pool
uint256 public pid; // this is unique to each pool
// keepCRV stuff
uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points)
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter, we send some extra CRV here
uint256 public constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips
// Swap stuff
address public constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV and CVX liquidity there
address[] public convexTokenPath; // path to sell CVX
IERC20 public constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 public constant convexToken =
IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20 public constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// keeper stuff
uint256 public harvestProfitNeeded; // we use this to set our dollar target (in USDT) for harvest sells
bool internal forceHarvestTriggerOnce; // only set this to true when we want to trigger our keepers to harvest for us
string internal stratName; // we use this to be able to adjust our strategy's name
// convex-specific variables
bool public claimRewards; // boolean if we should always claim rewards when withdrawing, usually withdrawAndUnwrap (generally this should be false)
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
// how much want we have staked in Convex
return IConvexRewards(rewardsContract).balanceOf(address(this));
}
function balanceOfWant() public view returns (uint256) {
// balance of want sitting in our strategy
return want.balanceOf(address(this));
}
function claimableBalance() public view returns (uint256) {
// how much CRV we can claim from the staking contract
return IConvexRewards(rewardsContract).earned(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== CONSTANT FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our Curve pool tokens to be deposited
uint256 _toInvest = balanceOfWant();
// deposit into convex and stake immediately but only if we have something to invest
if (_toInvest > 0) {
IConvexDeposit(depositContract).deposit(pid, _toInvest, true);
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(_stakedBal, _amountNeeded.sub(_wantBal)),
claimRewards
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
IConvexRewards(rewardsContract).withdrawAndUnwrap(
_stakedBal,
claimRewards
);
}
return balanceOfWant();
}
// Sells our harvested CVX into the selected output (ETH).
function _sellConvex(uint256 _convexAmount) internal {
IUniswapV2Router02(sushiswap).swapExactTokensForTokens(
_convexAmount,
uint256(0),
convexTokenPath,
address(this),
block.timestamp
);
}
// in case we need to exit into the convex deposit token, this will allow us to do that
// make sure to check claimRewards before this step if needed
// plan to have gov sweep convex deposit tokens from strategy after this
function withdrawToConvexDepositTokens() external onlyAuthorized {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdraw(_stakedBal, claimRewards);
}
}
// we don't want for these tokens to be swept out. We allow gov to sweep out cvx vault tokens; we would only be holding these if things were really, really rekt.
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// We usually don't need to claim rewards on withdrawals, but might change our mind for migrations etc
function setClaimRewards(bool _claimRewards) external onlyAuthorized {
claimRewards = _claimRewards;
}
// This determines when we tell our keepers to harvest based on profit. this is how much in USDT we need to make. remember, 6 decimals!
function setHarvestProfitNeeded(uint256 _harvestProfitNeeded)
external
onlyAuthorized
{
harvestProfitNeeded = _harvestProfitNeeded;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyConvexcvxCRV.sol
contract StrategyConvexcvxCRV is StrategyConvexBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
// Curve stuff
ICurveFi public curve; // Curve Pool, this is our pool specific to this vault
IERC20 public constant usdt =
IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
uint256 public maxGasPrice; // this is the max gas price we want our keepers to pay for harvests/tends
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
uint256 _pid,
address _curvePool,
string memory _name
) public StrategyConvexBase(_vault) {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 21 days; // 21 days in seconds
debtThreshold = 5 * 1e18; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 1_000_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy
harvestProfitNeeded = 80_000 * 1e6; // this is how much in USDT we need to make. remember, 6 decimals!
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// these are our standard approvals. want = Curve LP token
convexToken.approve(sushiswap, type(uint256).max);
want.approve(address(depositContract), type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// this is the pool specific to this vault, used for depositing
curve = ICurveFi(_curvePool);
// setup our rewards contract
pid = _pid; // this is the pool ID on convex, we use this to determine what the reweardsContract address is
address lptoken;
(lptoken, , , rewardsContract, , ) = IConvexDeposit(depositContract)
.poolInfo(_pid);
// check that our LP token based on our pid matches our want
require(address(lptoken) == address(want));
// set our strategy's name
stratName = _name;
// these are our approvals and path specific to this contract
crv.approve(address(curve), type(uint256).max);
// set our paths
convexTokenPath = [address(convexToken), address(weth), address(crv)];
// set our baseline max gas price
maxGasPrice = 75 * 1e9;
}
/* ========== VARIABLE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything we can claim, then harvest CRV and CVX from the rewards contract
if (claimableBalance() > 0) {
// this claims our CRV, CVX
IConvexRewards(rewardsContract).getReward(address(this), true);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
// send some of our CRV to our voter to boost yield (default 10%)
uint256 _sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (_sendToVoter > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
// sell our claimed CVX, no need to sell CRV since this pool accepts it as deposit
if (convexBalance > 0) {
_sellConvex(convexBalance);
}
// deposit our CRV to Curve
crvBalance = crv.balanceOf(address(this));
if (crvBalance > 0) {
curve.add_liquidity([crvBalance, 0], 0);
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(_stakedBal, _debtOutstanding),
claimRewards
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// migrate our want token to a new strategy if needed, make sure to check claimRewards first
// also send over any CRV or CVX that is claimed; for migrations we definitely want to claim
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
_stakedBal,
claimRewards
);
}
crv.safeTransfer(_newStrategy, crv.balanceOf(address(this)));
convexToken.safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// check if the base fee gas price is higher than we allow
if (readBaseFee() > maxGasPrice) {
return false;
}
// harvest if we have a profit to claim
if (claimableProfitInUsdt() > harvestProfitNeeded) {
return true;
}
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
return super.harvestTrigger(callCostinEth);
}
// we will need to add rewards token here if we have them
function claimableProfitInUsdt() internal view returns (uint256) {
// calculations pulled directly from CVX's contract for minting CVX per CRV claimed
uint256 totalCliffs = 1_000;
uint256 maxSupply = 100 * 1_000_000 * 1e18; // 100mil
uint256 reductionPerCliff = 100_000 * 1e18; // 100,000
uint256 supply = convexToken.totalSupply();
uint256 mintableCvx;
uint256 cliff = supply.div(reductionPerCliff);
uint256 _claimableBal = claimableBalance();
//mint if below total cliffs
if (cliff < totalCliffs) {
//for reduction% take inverse of current cliff
uint256 reduction = totalCliffs.sub(cliff);
//reduce
mintableCvx = _claimableBal.mul(reduction).div(totalCliffs);
//supply cap check
uint256 amtTillMax = maxSupply.sub(supply);
if (mintableCvx > amtTillMax) {
mintableCvx = amtTillMax;
}
}
address[] memory crv_usd_path = new address[](3);
crv_usd_path[0] = address(crv);
crv_usd_path[1] = address(weth);
crv_usd_path[2] = address(usdt);
address[] memory cvx_usd_path = new address[](3);
cvx_usd_path[0] = address(convexToken);
cvx_usd_path[1] = address(weth);
cvx_usd_path[2] = address(usdt);
uint256 crvValue;
if (_claimableBal > 0) {
uint256[] memory crvSwap =
IUniswapV2Router02(sushiswap).getAmountsOut(
_claimableBal,
crv_usd_path
);
crvValue = crvSwap[crvSwap.length - 1];
}
uint256 cvxValue;
if (mintableCvx > 0) {
uint256[] memory cvxSwap =
IUniswapV2Router02(sushiswap).getAmountsOut(
mintableCvx,
cvx_usd_path
);
cvxValue = cvxSwap[cvxSwap.length - 1];
}
return crvValue.add(cvxValue);
}
// convert our keeper's eth cost into want (we set this to return the value since it doesn't give much use)
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
return _ethAmount;
}
// use this to check current base fee gas price
function readBaseFee() internal view returns (uint256 baseFee) {
IBaseFee _baseFeeOracle =
IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549);
return _baseFeeOracle.basefee_global();
}
/* ========== SETTERS ========== */
// set the maximum gas price we want to pay for a harvest/tend in gwei
function setGasPrice(uint256 _maxGasPrice) external onlyAuthorized {
maxGasPrice = _maxGasPrice.mul(1e9);
}
} | migrate our want token to a new strategy if needed, make sure to check claimRewards first also send over any CRV or CVX that is claimed; for migrations we definitely want to claim | function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
_stakedBal,
claimRewards
);
}
crv.safeTransfer(_newStrategy, crv.balanceOf(address(this)));
convexToken.safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
| 236,481 | [
1,
22083,
3134,
2545,
1147,
358,
279,
394,
6252,
309,
3577,
16,
1221,
3071,
358,
866,
7516,
17631,
14727,
1122,
2546,
1366,
1879,
1281,
6732,
58,
578,
385,
58,
60,
716,
353,
7516,
329,
31,
364,
9814,
732,
2217,
25818,
2545,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
2911,
10224,
12,
2867,
389,
2704,
4525,
13,
2713,
3849,
288,
203,
3639,
2254,
5034,
389,
334,
9477,
38,
287,
273,
384,
9477,
13937,
5621,
203,
3639,
309,
261,
67,
334,
9477,
38,
287,
405,
374,
13,
288,
203,
5411,
467,
17467,
338,
17631,
14727,
12,
266,
6397,
8924,
2934,
1918,
9446,
1876,
984,
4113,
12,
203,
7734,
389,
334,
9477,
38,
287,
16,
203,
7734,
7516,
17631,
14727,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
4422,
90,
18,
4626,
5912,
24899,
2704,
4525,
16,
4422,
90,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
3639,
26213,
1345,
18,
4626,
5912,
12,
203,
5411,
389,
2704,
4525,
16,
203,
5411,
26213,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// 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 uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 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 => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract MinerOneToken is MintableToken {
using SafeMath for uint256;
string public name = "MinerOne";
string public symbol = "MIO";
uint8 public decimals = 18;
/**
* This struct holds data about token holder dividends
*/
struct Account {
/**
* Last amount of dividends seen at the token holder payout
*/
uint256 lastDividends;
/**
* Amount of wei contract needs to pay to token holder
*/
uint256 fixedBalance;
/**
* Unpayed wei amount due to rounding
*/
uint256 remainder;
}
/**
* Mapping which holds all token holders data
*/
mapping(address => Account) internal accounts;
/**
* Running total of all dividends distributed
*/
uint256 internal totalDividends;
/**
* Holds an amount of unpayed weis
*/
uint256 internal reserved;
/**
* Raised when payment distribution occurs
*/
event Distributed(uint256 amount);
/**
* Raised when shareholder withdraws his profit
*/
event Paid(address indexed to, uint256 amount);
/**
* Raised when the contract receives Ether
*/
event FundsReceived(address indexed from, uint256 amount);
modifier fixBalance(address _owner) {
Account storage account = accounts[_owner];
uint256 diff = totalDividends.sub(account.lastDividends);
if (diff > 0) {
uint256 numerator = account.remainder.add(balances[_owner].mul(diff));
account.fixedBalance = account.fixedBalance.add(numerator.div(totalSupply_));
account.remainder = numerator % totalSupply_;
account.lastDividends = totalDividends;
}
_;
}
modifier onlyWhenMintingFinished() {
require(mintingFinished);
_;
}
function () external payable {
withdraw(msg.sender, msg.value);
}
function deposit() external payable {
require(msg.value > 0);
require(msg.value <= this.balance.sub(reserved));
totalDividends = totalDividends.add(msg.value);
reserved = reserved.add(msg.value);
Distributed(msg.value);
}
/**
* Returns unpayed wei for a given address
*/
function getDividends(address _owner) public view returns (uint256) {
Account storage account = accounts[_owner];
uint256 diff = totalDividends.sub(account.lastDividends);
if (diff > 0) {
uint256 numerator = account.remainder.add(balances[_owner].mul(diff));
return account.fixedBalance.add(numerator.div(totalSupply_));
} else {
return 0;
}
}
function transfer(address _to, uint256 _value) public
onlyWhenMintingFinished
fixBalance(msg.sender)
fixBalance(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public
onlyWhenMintingFinished
fixBalance(_from)
fixBalance(_to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function payoutToAddress(address[] _holders) external {
require(_holders.length > 0);
require(_holders.length <= 100);
for (uint256 i = 0; i < _holders.length; i++) {
withdraw(_holders[i], 0);
}
}
/**
* Token holder must call this to receive dividends
*/
function withdraw(address _benefeciary, uint256 _toReturn) internal
onlyWhenMintingFinished
fixBalance(_benefeciary) returns (bool) {
uint256 amount = accounts[_benefeciary].fixedBalance;
reserved = reserved.sub(amount);
accounts[_benefeciary].fixedBalance = 0;
uint256 toTransfer = amount.add(_toReturn);
if (toTransfer > 0) {
_benefeciary.transfer(toTransfer);
}
if (amount > 0) {
Paid(_benefeciary, amount);
}
return true;
}
}
contract MinerOneCrowdsale is Ownable {
using SafeMath for uint256;
// Wallet where all ether will be
address public constant WALLET = 0x2C2b3885BC8B82Ad4D603D95ED8528Ef112fE8F2;
// Wallet for team tokens
address public constant TEAM_WALLET = 0x997faEf570B534E5fADc8D2D373e2F11aF4e115a;
// Wallet for research and development tokens
address public constant RESEARCH_AND_DEVELOPMENT_WALLET = 0x770998331D6775c345B1807c40413861fc4D6421;
// Wallet for bounty tokens
address public constant BOUNTY_WALLET = 0xd481Aab166B104B1aB12e372Ef7af6F986f4CF19;
uint256 public constant UINT256_MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint256 public constant ICO_TOKENS = 287000000e18;
uint8 public constant ICO_TOKENS_PERCENT = 82;
uint8 public constant TEAM_TOKENS_PERCENT = 10;
uint8 public constant RESEARCH_AND_DEVELOPMENT_TOKENS_PERCENT = 6;
uint8 public constant BOUNTY_TOKENS_PERCENT = 2;
uint256 public constant SOFT_CAP = 3000000e18;
uint256 public constant START_TIME = 1518692400; // 2018/02/15 11:00 UTC +0
uint256 public constant RATE = 1000; // 1000 tokens costs 1 ether
uint256 public constant LARGE_PURCHASE = 10000e18;
uint256 public constant LARGE_PURCHASE_BONUS = 4;
uint256 public constant TOKEN_DESK_BONUS = 3;
uint256 public constant MIN_TOKEN_AMOUNT = 100e18;
Phase[] internal phases;
struct Phase {
uint256 till;
uint8 discount;
}
// The token being sold
MinerOneToken public token;
// amount of raised money in wei
uint256 public weiRaised;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
uint256 public currentPhase = 0;
bool public isFinalized = false;
address private tokenMinter;
address private tokenDeskProxy;
uint256 public icoEndTime = 1526558400; // 2018/05/17 12:00 UTC +0
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
/**
* When there no tokens left to mint and token minter tries to manually mint tokens
* this event is raised to signal how many tokens we have to charge back to purchaser
*/
event ManualTokenMintRequiresRefund(address indexed purchaser, uint256 value);
function MinerOneCrowdsale(address _token) public {
phases.push(Phase({ till: 1519214400, discount: 35 })); // 2018/02/21 12:00 UTC +0
phases.push(Phase({ till: 1519905600, discount: 30 })); // 2018/03/01 12:00 UTC +0
phases.push(Phase({ till: 1521201600, discount: 25 })); // 2018/03/16 12:00 UTC +0
phases.push(Phase({ till: 1522584000, discount: 20 })); // 2018/04/01 12:00 UTC +0
phases.push(Phase({ till: 1524312000, discount: 15 })); // 2018/04/21 12:00 UTC +0
phases.push(Phase({ till: 1525608000, discount: 10 })); // 2018/05/06 12:00 UTC +0
phases.push(Phase({ till: 1526472000, discount: 5 })); // 2018/05/16 12:00 UTC +0
phases.push(Phase({ till: UINT256_MAX, discount:0 })); // unlimited
token = MinerOneToken(_token);
vault = new RefundVault(WALLET);
tokenMinter = msg.sender;
}
modifier onlyTokenMinterOrOwner() {
require(msg.sender == tokenMinter || msg.sender == owner);
_;
}
// fallback function can be used to buy tokens or claim refund
function () external payable {
if (!isFinalized) {
buyTokens(msg.sender, msg.sender);
} else {
claimRefund();
}
}
function mintTokens(address[] _receivers, uint256[] _amounts) external onlyTokenMinterOrOwner {
require(_receivers.length > 0 && _receivers.length <= 100);
require(_receivers.length == _amounts.length);
require(!isFinalized);
for (uint256 i = 0; i < _receivers.length; i++) {
address receiver = _receivers[i];
uint256 amount = _amounts[i];
require(receiver != address(0));
require(amount > 0);
uint256 excess = appendContribution(receiver, amount);
if (excess > 0) {
ManualTokenMintRequiresRefund(receiver, excess);
}
}
}
// low level token purchase function
function buyTokens(address sender, address beneficiary) public payable {
require(beneficiary != address(0));
require(sender != address(0));
require(validPurchase());
uint256 weiReceived = msg.value;
uint256 nowTime = getNow();
// this loop moves phases and insures correct stage according to date
while (currentPhase < phases.length && phases[currentPhase].till < nowTime) {
currentPhase = currentPhase.add(1);
}
// calculate token amount to be created
uint256 tokens = calculateTokens(weiReceived);
if (tokens < MIN_TOKEN_AMOUNT) revert();
uint256 excess = appendContribution(beneficiary, tokens);
uint256 refund = (excess > 0 ? excess.mul(weiReceived).div(tokens) : 0);
weiReceived = weiReceived.sub(refund);
weiRaised = weiRaised.add(weiReceived);
if (refund > 0) {
sender.transfer(refund);
}
TokenPurchase(sender, beneficiary, weiReceived, tokens.sub(excess));
if (goalReached()) {
WALLET.transfer(weiReceived);
} else {
vault.deposit.value(weiReceived)(sender);
}
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public onlyOwner {
require(!isFinalized);
require(hasEnded());
if (goalReached()) {
vault.close();
uint256 totalSupply = token.totalSupply();
uint256 teamTokens = uint256(TEAM_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT);
token.mint(TEAM_WALLET, teamTokens);
uint256 rdTokens = uint256(RESEARCH_AND_DEVELOPMENT_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT);
token.mint(RESEARCH_AND_DEVELOPMENT_WALLET, rdTokens);
uint256 bountyTokens = uint256(BOUNTY_TOKENS_PERCENT).mul(totalSupply).div(ICO_TOKENS_PERCENT);
token.mint(BOUNTY_WALLET, bountyTokens);
token.finishMinting();
token.transferOwnership(token);
} else {
vault.enableRefunds();
}
Finalized();
isFinalized = true;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return getNow() > icoEndTime || token.totalSupply() == ICO_TOKENS;
}
function goalReached() public view returns (bool) {
return token.totalSupply() >= SOFT_CAP;
}
function setTokenMinter(address _tokenMinter) public onlyOwner {
require(_tokenMinter != address(0));
tokenMinter = _tokenMinter;
}
function setTokenDeskProxy(address _tokekDeskProxy) public onlyOwner {
require(_tokekDeskProxy != address(0));
tokenDeskProxy = _tokekDeskProxy;
}
function setIcoEndTime(uint256 _endTime) public onlyOwner {
require(_endTime > icoEndTime);
icoEndTime = _endTime;
}
function getNow() internal view returns (uint256) {
return now;
}
function calculateTokens(uint256 _weiAmount) internal view returns (uint256) {
uint256 tokens = _weiAmount.mul(RATE).mul(100).div(uint256(100).sub(phases[currentPhase].discount));
uint256 bonus = 0;
if (currentPhase > 0) {
bonus = bonus.add(tokens >= LARGE_PURCHASE ? LARGE_PURCHASE_BONUS : 0);
bonus = bonus.add(msg.sender == tokenDeskProxy ? TOKEN_DESK_BONUS : 0);
}
return tokens.add(tokens.mul(bonus).div(100));
}
function appendContribution(address _beneficiary, uint256 _tokens) internal returns (uint256) {
uint256 excess = 0;
uint256 tokensToMint = 0;
uint256 totalSupply = token.totalSupply();
if (totalSupply.add(_tokens) < ICO_TOKENS) {
tokensToMint = _tokens;
} else {
tokensToMint = ICO_TOKENS.sub(totalSupply);
excess = _tokens.sub(tokensToMint);
}
if (tokensToMint > 0) {
token.mint(_beneficiary, tokensToMint);
}
return excess;
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = getNow() >= START_TIME && getNow() <= icoEndTime;
bool nonZeroPurchase = msg.value != 0;
bool canMint = token.totalSupply() < ICO_TOKENS;
bool validPhase = (currentPhase < phases.length);
return withinPeriod && nonZeroPurchase && canMint && validPhase;
}
} | * Raised when shareholder withdraws his profit/ | event Paid(address indexed to, uint256 amount);
| 12,987,429 | [
1,
12649,
5918,
1347,
7433,
4505,
598,
9446,
87,
18423,
450,
7216,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
453,
20736,
12,
2867,
8808,
358,
16,
2254,
5034,
3844,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../interface/IERC20.sol";
import "../interface/ILToken.sol";
import "./ERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title Deri Protocol liquidity provider token implementation
*/
contract LToken is IERC20, ILToken, ERC20 {
using UnsignedSafeMath for uint256;
// Pool address this LToken associated with
address private _pool;
modifier _pool_() {
require(msg.sender == _pool, "LToken: called by non-associative pool, probably the original pool has been migrated");
_;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token
*/
constructor(string memory name_, string memory symbol_, address pool_) ERC20(name_, symbol_) {
require(pool_ != address(0), "LToken: construct with 0 address pool");
_pool = pool_;
}
/**
* @dev See {ILToken}.{setPool}
*/
function setPool(address newPool) public override {
require(newPool != address(0), "LToken: setPool to 0 address");
require(msg.sender == _pool, "LToken: setPool caller is not current pool");
_pool = newPool;
}
/**
* @dev See {ILToken}.{pool}
*/
function pool() public view override returns (address) {
return _pool;
}
/**
* @dev See {ILToken}.{mint}
*/
function mint(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: mint to 0 address");
_balances[account] = _balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev See {ILToken}.{burn}
*/
function burn(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: burn from 0 address");
require(_balances[account] >= amount, "LToken: burn amount exceeds balance");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
// 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 Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() external view returns (string memory);
/**
* @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() external view returns (uint8);
/**
* @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 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 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 Moves `amount` tokens from `from` to `to` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC20.sol";
/**
* @title Deri Protocol liquidity provider token interface
*/
interface ILToken is IERC20 {
/**
* @dev Set the pool address of this LToken
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of pool
*/
function pool() external view returns (address);
/**
* @dev Mint LToken to `account` of `amount`
*
* Can only be called by pool
* `account` cannot be zero address
*/
function mint(address account, uint256 amount) external;
/**
* @dev Burn `amount` LToken of `account`
*
* Can only be called by pool
* `account` cannot be zero address
* `account` must owns at least `amount` LToken
*/
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title ERC20 Implementation
*/
contract ERC20 is IERC20 {
using UnsignedSafeMath for uint256;
string _name;
string _symbol;
uint8 _decimals = 18;
uint256 _totalSupply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC20}.{name}
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC20}.{symbol}
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC20}.{decimals}
*/
function decimals() public view override 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}.{allowance}
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20}.{approve}
*/
function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20}.{transfer}
*/
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
/**
* @dev See {IERC20}.{transferFrom}
*/
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`.
* Emits an {Approval} event.
*
* Parameters check should be carried out before calling this function.
*/
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves tokens `amount` from `from` to `to`.
* Emits a {Transfer} event.
*
* Parameters check should be carried out before calling this function.
*/
function _transfer(address from, address to, uint256 amount) internal {
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Unsigned safe math
*/
library UnsignedSafeMath {
/**
* @dev Addition of unsigned integers, counterpart to `+`
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
/**
* @dev Subtraction of unsigned integers, counterpart to `-`
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Multiplication of unsigned integers, counterpart to `*`
*/
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Division of unsigned integers, counterpart to `/`
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
/**
* @dev Modulo of unsigned integers, counterpart to `%`
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
} | * @title Unsigned safe math/ | library UnsignedSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: 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, "UnsignedSafeMath: multiplication overflow");
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
} | 10,376,719 | [
1,
13290,
4183,
4233,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
1351,
5679,
9890,
10477,
288,
203,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
13290,
9890,
10477,
30,
2719,
9391,
8863,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
69,
1545,
324,
16,
315,
13290,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
13290,
9890,
10477,
30,
23066,
9391,
8863,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import { IERC20 } from "./interfaces/IERC20.sol";
import { IExchange } from "./interfaces/IExchange.sol";
import { console } from "hardhat/console.sol"; // TODO: Remove
library Errors {
string internal constant _AmountZero = "Amount can't be 0";
string internal constant _DurationZero = "Duration can't be 0";
string internal constant _NothingToSell = "Nothing to sell";
string internal constant _FunctionCalledToday = "Function already called today";
}
contract CronSwapper {
struct Allocation {
uint256 id;
uint256 amount;
uint256 startDay;
uint256 endDay;
address owner;
}
IERC20 public immutable toSell;
IERC20 public immutable toBuy;
IExchange public immutable exchange;
uint256 public dailyAmount;
uint256 public lastExecution;
uint256 public nextAllocationId;
mapping(uint256 => uint256) public removeAmount;
mapping(uint256 => Allocation) public allocations;
mapping(uint256 => uint256) public toBuyPriceCumulative;
event Swap(uint256 indexed toSellSold, uint256 toBuyBought, uint256 toBuyPrice);
event Enter(uint256 indexed id, address indexed sender, uint256 indexed amount, uint256 startDay, uint256 endDay);
constructor(
IERC20 toSell_,
IERC20 toBuy_,
IExchange exchange_
) {
toSell = toSell_;
toBuy = toBuy_;
exchange = exchange_;
lastExecution = _today();
}
function enter(uint256 amount, uint256 duration) external returns (uint256) {
require(amount > 0, Errors._AmountZero);
require(duration > 0, Errors._DurationZero);
uint256 total = amount * duration;
IERC20(toSell).transferFrom(msg.sender, address(this), total);
uint256 startDay = _today();
if (lastExecution == startDay) {
startDay += 1;
}
// We have to subtract 1 from the `duration` given that we'll also swap
// on the `startDay`
// If we have a duration of 1, the `endDay` should be the `startDay`
// If we have a duration of 2, the `endDay` should be the `startDay` + 1
// ...
uint256 endDay = startDay + duration - 1;
dailyAmount += amount;
removeAmount[endDay] += amount;
uint256 id = nextAllocationId;
nextAllocationId++;
allocations[id] = Allocation({ id: id, amount: amount, startDay: startDay, endDay: endDay, owner: msg.sender });
emit Enter(id, msg.sender, amount, startDay, endDay);
return id;
}
function swap() external returns (uint256, uint256) {
uint256 today = _today();
require(lastExecution < today, Errors._FunctionCalledToday);
require(dailyAmount > 0, Errors._NothingToSell);
toSell.approve(address(exchange), dailyAmount);
uint256 toBuyBought = exchange.swap(toSell, toBuy, dailyAmount);
uint256 toSellSold = dailyAmount;
// uint256 toBuyPrice = toBuyBought / dailyAmount;
// uint256 scaledToBuyBought = toBuyBought; // * 10**uint256(toBuy.decimals());
// uint256 scaledDailyAmouny = dailyAmount * 10**uint256(toBuy.decimals() - toSell.decimals());
// uint256 toBuyPrice = scaledToBuyBought / scaledDailyAmouny;
// uint256 toBuyPrice = (toBuyBought * 10**uint256(toBuy.decimals() - toSell.decimals())) / dailyAmount;
// TODO: This works (kind of)
// uint256 toBuyPrice = ((toSellSold * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought) *
// 10**uint256(toSell.decimals());
// uint256 toBuyPrice = (toSellSold * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought;
// TODO: Similar solution to the one above but based on the insights from below
// uint256 toBuyPrice = ((((toSellSold * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought)) *
// 10**uint256(toSell.decimals() - 6));
// TODO: This is the result of the `toBuyPrice` in wei (don't touch)
// TODO: Try to simplify (e.g. remove the rescaling)
// uint256 toBuyPrice =
// ((((toSellSold * 1e18 * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought) *
// 1e18) * 10**uint256(toSell.decimals() - 6)) / 1e18;
// TODO: Test this by buing USDC with WETH (it should also be denominated in 1e18)
// uint256 toBuyPrice = (
// (((toSellSold * 1e18 * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought) * 1e18)
// ) / 1e18;
// uint256 toBuyPrice = (
// (((toSellSold * 1e18 * 10**uint256(toBuy.decimals() - toSell.decimals())) / toBuyBought) * 1e18)
// ) /
// 1e18 /
// 1e12;
// uint256 toBuyPrice = (toSellSold * 1e18) / toBuyBought;
uint256 toBuyPrice = (toSellSold * 10**uint256(toBuy.decimals())) / toBuyBought; // <-- simplest solution
console.log("toBuyBought: %s", toBuyBought);
console.log("toSellSold: %s", toSellSold);
console.log("toBuyPrice: %s", toBuyPrice);
//5000000000000000000000
toBuyPriceCumulative[today] += toBuyPriceCumulative[lastExecution] + toBuyPrice;
uint256 amountToRemove = _calcAmountToRemove();
dailyAmount -= amountToRemove;
lastExecution = today;
emit Swap(toSellSold, toBuyBought, toBuyPrice);
return (toBuyBought, toBuyPrice);
}
function toBuyBalance(uint256 id) external view returns (uint256) {
Allocation memory allocation = allocations[id];
// uint256 cumulativePrice = toBuyPriceCumulative[lastDay] - toBuyPriceCumulative[startDay];
uint256 cumulativePrice = _findNearestCumulativeToBuyPrice(allocation.startDay, allocation.endDay);
// TODO: Find
console.log("cumulativePrice: %s", cumulativePrice); // TODO:
// TODO: do we need to divide by 1e18 here given that the USDC value in in wei?
return cumulativePrice * allocation.amount;
}
function _today() private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp / 1 days;
}
// NOTE: The number of iterations is "bound" given that a (large) gap between
// executions should be a rare occasion
function _findNearestCumulativeToBuyPrice(uint256 startDay, uint256 endDay) private view returns (uint256) {
uint256 i;
uint256 cumulativePrice;
while (cumulativePrice == 0 && startDay != endDay) {
cumulativePrice = toBuyPriceCumulative[endDay - i];
i += 1;
}
return cumulativePrice;
}
// NOTE: The number of iterations is "bound" given that a (large) gap between
// executions should be a rare occasion
function _calcAmountToRemove() private view returns (uint256) {
uint256 amountToRemove;
uint256 today = _today();
uint256 dayDiff = today - lastExecution;
for (uint256 i = 0; i < dayDiff; i++) {
amountToRemove += removeAmount[today - i];
}
return amountToRemove;
}
}
| NOTE: The number of iterations is "bound" given that a (large) gap between executions should be a rare occasion | function _findNearestCumulativeToBuyPrice(uint256 startDay, uint256 endDay) private view returns (uint256) {
uint256 i;
uint256 cumulativePrice;
while (cumulativePrice == 0 && startDay != endDay) {
cumulativePrice = toBuyPriceCumulative[endDay - i];
i += 1;
}
return cumulativePrice;
}
| 2,514,581 | [
1,
17857,
30,
1021,
1300,
434,
11316,
353,
315,
3653,
6,
864,
716,
279,
261,
14095,
13,
9300,
3086,
225,
26845,
1410,
506,
279,
25671,
9145,
345,
285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4720,
28031,
39,
11276,
774,
38,
9835,
5147,
12,
11890,
5034,
787,
4245,
16,
2254,
5034,
679,
4245,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
277,
31,
203,
3639,
2254,
5034,
15582,
5147,
31,
203,
3639,
1323,
261,
71,
11276,
5147,
422,
374,
597,
787,
4245,
480,
679,
4245,
13,
288,
203,
5411,
15582,
5147,
273,
358,
38,
9835,
5147,
39,
11276,
63,
409,
4245,
300,
277,
15533,
203,
5411,
277,
1011,
404,
31,
203,
3639,
289,
203,
3639,
327,
15582,
5147,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Credits.sol";
// ----------------------------------------------------------------------------
//
// (c) The BotNet Project 2020
//
// ----------------------------------------------------------------------------
// TO DO...
// [ ] Fix deposit & withdraw functions
contract SwapBot {
using SafeMath for uint256;
Credits credits;
address public feeAccount; // the account that receives exchange fees
uint256 public feePercent; // the fee percentage
address constant ETHER = address(0); // store Ether in credits mapping with blank address
mapping(address => mapping(address => uint256)) public creditsAvailable; // ether & credits available
mapping(uint256 => _Order) public orders; // storage of the different orders
uint256 public orderCount;
mapping(uint256 => bool) public orderCancelled;
mapping(uint256 => bool) public orderFilled;
event Deposit(
address token,
address user,
uint256 amount,
uint256 balance
);
event Withdraw(
address token,
address user,
uint256 amount,
uint256 balance
);
event Order(
uint256 id,
address user,
address tokenGet,
uint256 amountGet,
address tokenGive,
uint256 amountGive,
uint256 timestamp
);
event Cancel(
uint256 id,
address user,
address tokenGet,
uint256 amountGet,
address tokenGive,
uint256 amountGive,
uint256 timestamp
);
event Trade(
uint256 id,
address user,
address tokenGet,
uint256 amountGet,
address tokenGive,
uint256 amountGive,
address userFill,
uint256 timestamp
);
// template to add orders
struct _Order {
uint256 id;
address user; // the person who create the order
address tokenGet; // token user wants to purchase
uint256 amountGet; // the amount of the token they want to get
address tokenGive; // the token they're going to use in the trade
uint256 amountGive; // the amount of the token they're going to trade
uint256 timestamp; // time of when the order was created
}
constructor (address _feeAccount, uint256 _feePercent) {
feeAccount = _feeAccount;
feePercent = _feePercent;
}
// Fallback: reverts if Ether is sent to this smart contract by mistake
fallback() external {
revert();
}
function depositEther() payable public {
creditsAvailable[ETHER][msg.sender] = creditsAvailable[ETHER][msg.sender].add(msg.value);
emit Deposit(ETHER, msg.sender, msg.value, creditsAvailable[ETHER][msg.sender]);
}
function withdrawEther(uint _amount) public {
require(creditsAvailable[ETHER][msg.sender] >= _amount);
creditsAvailable[ETHER][msg.sender] = creditsAvailable[ETHER][msg.sender].sub(_amount);
msg.sender.transfer(_amount);
emit Withdraw(ETHER, msg.sender, _amount, creditsAvailable[ETHER][msg.sender]);
}
function depositCredits(address _token, uint _amount) public {
require(_token != ETHER);
// require(Credits(_token).transferFrom(msg.sender, address(this), _amount));
// require(credits.transfer(address(this), _amount));
creditsAvailable[_token][msg.sender] = creditsAvailable[_token][msg.sender].add(_amount);
emit Deposit(_token, msg.sender, _amount, creditsAvailable[_token][msg.sender]);
}
function withdrawCredits(address _token, uint256 _amount) public {
require(_token != ETHER);
require(creditsAvailable[_token][msg.sender] >= _amount);
creditsAvailable[_token][msg.sender] = creditsAvailable[_token][msg.sender].sub(_amount);
// require(Credits(_token). transfer(msg.sender, _amount));
emit Withdraw(_token, msg.sender, _amount, creditsAvailable[_token][msg.sender]);
}
function balanceOf(address _token, address _user) public view returns (uint256) {
return creditsAvailable[_token][_user];
}
function makeOrder(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) public {
orderCount = orderCount.add(1);
orders[orderCount] = _Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, block.timestamp);
emit Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, block.timestamp);
}
function cancelOrder(uint256 _id) public {
_Order storage _order = orders[_id];
require(address(_order.user) == msg.sender); // order must be the user's
require(_order.id == _id); // the order must exist
orderCancelled[_id] = true;
emit Cancel(_order.id, msg.sender, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive, block.timestamp);
}
function fillOrder(uint256 _id) public {
require(_id > 0 && _id <= orderCount);
require(!orderFilled[_id]);
require(!orderCancelled[_id]);
_Order storage _order = orders[_id];
_trade(_order.id, _order.user, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive);
orderFilled[_order.id] = true;
}
function _trade(uint256 _orderId, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) internal {
// Fee paid by the user that fills the order, a.k.a. msg.sender.
uint256 _feeAmount = _amountGet.mul(feePercent).div(100); // 10% fee
// Execute trade
creditsAvailable[_tokenGet][msg.sender] = creditsAvailable[_tokenGet][msg.sender].sub(_amountGet.add(_feeAmount));
creditsAvailable[_tokenGet][_user] = creditsAvailable[_tokenGet][_user].add(_amountGet);
creditsAvailable[_tokenGet][feeAccount] = creditsAvailable[_tokenGet][feeAccount].add(_feeAmount);
creditsAvailable[_tokenGive][_user] = creditsAvailable[_tokenGive][_user].sub(_amountGive);
creditsAvailable[_tokenGive][msg.sender] = creditsAvailable[_tokenGive][msg.sender].add(_amountGive);
emit Trade(_orderId, _user, _tokenGet, _amountGet, _tokenGive, _amountGive, msg.sender, block.timestamp);
}
}
| the account that receives exchange fees
| address public feeAccount; | 5,506,772 | [
1,
5787,
2236,
716,
17024,
7829,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
1071,
14036,
3032,
31,
4766,
10402,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "zeppelin/contracts/ownership/Ownable.sol";
import "zeppelin/contracts/lifecycle/Destructible.sol";
/** @title OnlineMarketplace. */
contract OnlineMarketplace is Ownable,Destructible {
/**A struct type.
Creates a product struct
*/
struct Product {
string name; // name of the product
uint sku; // sku #
uint price; // price
uint qty; // quantity
State state; // Current state
address buyer;
uint index; // pointer to the index in productIndex;
}
/**A struct type.
Creates a Store front struct.
*/
struct StoreFront {
string name; // name of the store front
address owner; // owner of the store
uint balance; // funds collected in the store
mapping(uint => Product) products; // products in the store
uint[] productIndex; // array to track number of prducts
uint index; //pointer to the index in storeFrontINdex
}
struct User
{
uint role;
bool isActive;
}
/** An enum type.
*/
enum State {
ForSale,
Sold,
Removed
}
/**Set the owner
*/
address owner;
/* Track the most recent sku # */
uint skuCount;
mapping(address => User) private users; // The administrator list.
// mapping(address => bool) private approvedStoreOwners; // The store owner list.
mapping(bytes32 => StoreFront) private storeFronts; //The storefronts.
bytes32[] storeFrontIndex; // Array to track the store fronts.
event AddAdministrator(address _administratorAddress);
event AddStoreOwner(address _storeOwnerAddress);
event CreateStoreFront(bytes32 _storeFrontId, string _name, address _owner);
event ForSale(bytes32 _storeFrontId, string _productName, uint _sku, uint _qty);
event ChangePrice(bytes32 _storeFrontId, uint _sku,uint _oldPrice, uint _newPrice);
event Sold(bytes32 _storeFrontId, uint _sku, uint _qty, address _buyer);
event Removed(bytes32 _storeFrontId, uint _sku);
event Withdraw(bytes32 _storeFrontId, uint _balance);
event LogSender(address _address);
/* Checks if msg.sender is the owner of the contract */
modifier isOwner() {
require(owner == msg.sender);
_;
}
/* Checks if msg.sender is an administrator */
modifier verifyIsAdmin() {
require(isAdmin(msg.sender));
_;
}
/* Checks if msg.sender is an approved store owner */
modifier verifyIsApprovedStoreOwner() {
require(isApprovedStoreOwner(msg.sender));
_;
}
/* Checks if msg.sender is the expected address value. */
modifier verifyCaller (address _address) {
require (msg.sender == _address);
_;
}
modifier checkValue(bytes32 _storeFrontId, uint _sku) {
//refund them after pay for item (why it is before, _ checks for logic before func)
_;
uint _price = storeFronts[_storeFrontId].products[_sku].price;
uint amountToRefund = msg.value - _price;
storeFronts[_storeFrontId].products[_sku].buyer.transfer(amountToRefund);
}
modifier forSale(bytes32 _storeFrontId, uint sku) {
require(storeFronts[_storeFrontId].products[sku].state == State.ForSale);
_;
}
modifier paidEnough(uint _price) {
require(msg.value >= _price);
_;
}
modifier qtyAvailable(bytes32 _storeFrontId, uint _sku, uint _qty) {
require(storeFronts[_storeFrontId].products[_sku].qty >= _qty);
_;
}
/**Constructor.
@dev Instantiates the skuCount to 0. Sets owner to msg.sender.
*/
constructor()
public
{
owner = msg.sender;
skuCount = 0;
}
function ()
public
{
emit LogSender(msg.sender);
}
/** Checks if the passed address is an administrator
* @param _address THe address to check.
* @return success
*/
function isAdmin(address _address)
public
view
returns (bool success)
{
return users[_address].isActive && users[_address].role == 1;
}
/**
* @dev Adds the provided address as an administrator.
* @param _address Address of the store owner.
* @return success
*/
function addAdministrator(address _address)
public
isOwner
returns (bool success)
{
users[_address] = User({role:1,isActive:true});
emit AddAdministrator(_address);
return true;
}
/**
* @dev Adds the provided address as an approved store owner.
* @param _address address of the store owner.
* @return success
*/
function addStoreOwner(address _address)
public
verifyIsAdmin
returns (bool success)
{
users[_address] = User({role:2,isActive:true});
emit AddStoreOwner(_address);
return true;
}
/**Check if the passed address is an approved store owners
* @param _address The address to check.
* @return success
*/
function isApprovedStoreOwner(address _address)
public
view
returns (bool success)
{
return users[_address].isActive && users[_address].role == 2;
}
/**Check if the passed address is a valid user
* @return success
*/
function login()
public
view
returns (uint role)
{
if (users[msg.sender].role != 0) {
return users[msg.sender].role;
} else {
return 401;
}
}
/**Crate a store front
* @param _name name of the store front
* @return success
*/
function createStoreFront(string _name)
public
verifyIsApprovedStoreOwner
returns (bool success)
{
bytes32 _storeFrontId = keccak256(abi.encodePacked(_name));
storeFrontIndex.push(_storeFrontId);
storeFronts[_storeFrontId].name = _name;
storeFronts[_storeFrontId].owner = msg.sender;
storeFronts[_storeFrontId].index = storeFrontIndex.length - 1;
emit CreateStoreFront(_storeFrontId, _name, msg.sender);
return true;
}
/**
* @dev Returns the number of store fronts
* @return numberOfStoreFronts
*/
function getStoreFrontCount()
public
view
returns (uint numberOfStoreFronts)
{
return storeFrontIndex.length;
}
/**
* @dev Returns the store front details.
* @param _index The index
* @return storeFrontId The storeFrontId stored at this index.
*/
function getStoreFrontIdByIndex(uint _index)
public
view
returns (bytes32 storeFrontId)
{
return (storeFrontIndex[_index]);
}
/**
* @dev Returns the store front details.
* @param _storeFrontId The id of the store front
* @return storeFrontName The name of the store front
* @return storeOwner The address of the store owner
*/
function getStoreFront(bytes32 _storeFrontId)
public
view
returns (string storeFrontName, address storeOwner)
{
return (storeFronts[_storeFrontId].name, storeFronts[_storeFrontId].owner);
}
/**
* @dev Returns the store front balance.
* @param _storeFrontId The id of the store front
* @return _balance
*/
function getStoreBalance(bytes32 _storeFrontId)
public
view
returns (uint _balance)
{
return storeFronts[_storeFrontId].balance;
}
/**
* @dev Add product to the store
* @param _storeFrontId The id of the store front
* @param _name The name of the product
* @param _price The price of the product
* @return success
*/
function addProduct(bytes32 _storeFrontId, string _name, uint _price, uint _qty)
public
verifyIsApprovedStoreOwner
returns (bool success)
{
storeFronts[_storeFrontId].productIndex.push(skuCount);
storeFronts[_storeFrontId].products[skuCount] = Product({
name: _name,
sku: skuCount,
price: _price,
qty: _qty,
state: State.ForSale,
buyer: 0,
index: storeFronts[_storeFrontId].productIndex.length - 1
});
emit ForSale(_storeFrontId, _name, skuCount, _qty);
skuCount = skuCount + 1;
return true;
}
/** Get the number of products in a store
* @param _storeFrontId The id of the store front
* @return productCount The count of products in a store.
*/
function getProductCountForAStore(bytes32 _storeFrontId)
public
view
returns (uint productCount)
{
return storeFronts[_storeFrontId].productIndex.length;
}
/** Get the product id stored at the provided index
* @param _storeFrontId The id of the store front
* @param _index Index to look at.
* @return productId The count of products in a store.
*/
function getProductIdStoredAtIndex(bytes32 _storeFrontId, uint _index)
public
view
returns (uint productId)
{
return storeFronts[_storeFrontId].productIndex[_index];
}
/** Get the product id stored at the provided index
* @param _storeFrontId The id of the store front
* @param _sku The product Id to get detail about
* @return _name The name of the product.
* @return _price The price of the product
* @return _qty the quantity available
* @return _buyer The buyer.
* @return _state The prodcut state.
* @return _index
*/
function getProduct(bytes32 _storeFrontId, uint _sku)
public
view
returns (uint sku, string _name, uint _price, uint _qty, uint _index)
{
return (
_sku,
storeFronts[_storeFrontId].products[_sku].name,
storeFronts[_storeFrontId].products[_sku].price,
storeFronts[_storeFrontId].products[_sku].qty,
storeFronts[_storeFrontId].products[_sku].index
);
}
/**
* @dev Remove product to tghe store
* @param _storeFrontId The id of the store front
* @param _sku The sku # of the product
*/
function removeProduct(bytes32 _storeFrontId, uint _sku)
public
verifyIsApprovedStoreOwner
{
emit Removed(_storeFrontId, _sku);
uint rowToDelete = storeFronts[_storeFrontId].products[_sku].index;
storeFronts[_storeFrontId].products[_sku].state = State.Removed;
uint skuToMove = storeFronts[_storeFrontId].productIndex[storeFronts[_storeFrontId].productIndex.length - 1];
storeFronts[_storeFrontId].productIndex[rowToDelete] = skuToMove;
storeFronts[_storeFrontId].products[skuToMove].index = rowToDelete;
storeFronts[_storeFrontId].productIndex.length--;
}
/**
* @dev Change price for a product
* @param _storeFrontId The id of the store front
* @param _sku The sku # of the product
* @param _newPrice The new price for the product
*/
function changePrice(bytes32 _storeFrontId, uint _sku, uint _newPrice)
public
verifyIsApprovedStoreOwner
{
uint _oldPrice = storeFronts[_storeFrontId].products[_sku].price;
storeFronts[_storeFrontId].products[_sku].price = _newPrice;
emit ChangePrice(_storeFrontId, _sku, _oldPrice, _newPrice);
}
/**
* @dev Buyer buys a product
* @param _storeFrontId The id of the store front
* @param _sku The sku # of the product
* @return success
*/
function purchaseProduct(bytes32 _storeFrontId, uint _sku, uint _qty)
public
payable
// forSale(_storeFrontId, _sku)
paidEnough(storeFronts[_storeFrontId].products[_sku].price)
qtyAvailable(_storeFrontId, _sku, _qty)
// checkValue(_storeFrontId, _sku)
{
storeFronts[_storeFrontId].balance = storeFronts[_storeFrontId].balance + storeFronts[_storeFrontId].products[_sku].price;
storeFronts[_storeFrontId].products[_sku].state = State.Sold;
storeFronts[_storeFrontId].products[_sku].buyer = msg.sender;
storeFronts[_storeFrontId].products[_sku].qty = storeFronts[_storeFrontId].products[_sku].qty - _qty;
emit Sold(_storeFrontId, _sku, _qty, msg.sender);
}
/**
* @dev Withdraw funds from a store and send it to the owner of the store front
* @param _storeFrontId The id of the store front
*/
function withdraw(bytes32 _storeFrontId)
public
verifyIsApprovedStoreOwner
{
uint _balance = storeFronts[_storeFrontId].balance;
emit Withdraw(_storeFrontId, _balance);
storeFronts[_storeFrontId].balance = 0;
storeFronts[_storeFrontId].owner.transfer(_balance);
}
} | The administrator list.
| mapping(address => User) private users; | 12,622,947 | [
1,
1986,
22330,
666,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2177,
13,
3238,
3677,
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
] |
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
pragma experimental "ABIEncoderV2";
import { Authorizable } from "../../lib/Authorizable.sol";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { ERC20Wrapper as ERC20 } from "../../lib/ERC20Wrapper.sol";
import { IExchange as ZeroExExchange } from "../../external/0x/Exchange/interfaces/IExchange.sol";
import { LibBytes } from "../../external/0x/LibBytes.sol";
import { LibFillResults as ZeroExFillResults } from "../../external/0x/Exchange/libs/LibFillResults.sol";
import { LibOrder as ZeroExOrder } from "../../external/0x/Exchange/libs/LibOrder.sol";
import { ZeroExOrderDataHandler as OrderHandler } from "./lib/ZeroExOrderDataHandler.sol";
/**
* @title ZeroExExchangeWrapper
* @author Set Protocol
*
* The ZeroExExchangeWrapper contract wrapper to interface with 0x V2
*/
contract ZeroExExchangeWrapper is
Authorizable
{
using SafeMath for uint256;
using LibBytes for bytes;
/* ============ State Variables ============ */
address public zeroExExchange;
address public zeroExProxy;
address public setTransferProxy;
/* ============ Constructor ============ */
/**
* Initialize exchange wrapper with required addresses to facilitate 0x orders
*
* @param _zeroExExchange 0x Exchange contract for filling orders
* @param _zeroExProxy 0x Proxy contract for transferring
* @param _setTransferProxy Set Protocol transfer proxy contract
*/
constructor(
address _zeroExExchange,
address _zeroExProxy,
address _setTransferProxy
)
public
Authorizable(2592000) // about 4 weeks
{
zeroExExchange = _zeroExExchange;
zeroExProxy = _zeroExProxy;
setTransferProxy = _setTransferProxy;
}
/* ============ Public Functions ============ */
/**
* IExchangeWrapper interface delegate method.
* Parses 0x exchange orders and transfers tokens from taker's wallet.
*
* TODO: We are currently assuming no taker fee. Add in taker fee going forward
*
* @param _ Unused address of fillOrder caller to conform to IExchangeWrapper
* @param _orderCount Amount of orders in exchange request
* @param _ordersData Byte string containing (multiple) 0x wrapper orders
* @return address[] Array of token addresses executed in orders
* @return uint256[] Array of token amounts executed in orders
*/
function exchange(
address _,
uint256 _orderCount,
bytes _ordersData
)
external
onlyAuthorized
returns (address[], uint256[])
{
address[] memory takerTokens = new address[](_orderCount);
uint256[] memory takerAmounts = new uint256[](_orderCount);
uint256 scannedBytes = 0;
for (uint256 i = 0; i < _orderCount; i++) {
// Parse header of current wrapper order
OrderHandler.OrderHeader memory header = OrderHandler.parseOrderHeader(
_ordersData,
scannedBytes
);
// Helper reduce math, keeping the position of the start of the next 0x order body
uint256 orderBodyStart = scannedBytes.add(header.signatureLength).add(160);
// Grab signature of current wrapper order after the header of length 160 and before the start of the body
bytes memory signature = _ordersData.slice(
scannedBytes.add(160),
orderBodyStart
);
// Parse 0x order of current wrapper order
ZeroExOrder.Order memory order = OrderHandler.parseZeroExOrder(
_ordersData,
header,
orderBodyStart
);
// Fill the order via the 0x exchange
(takerTokens[i], takerAmounts[i]) = fillZeroExOrder(
order,
signature,
header
);
// Update current bytes
scannedBytes = orderBodyStart.add(header.orderLength);
}
return (
takerTokens,
takerAmounts
);
}
/* ============ Private ============ */
/**
* Executes 0x order from signed order data
*
* @param _order 0x order struct
* @param _signature Signature for order
* @param _header Struct containing wrapper order header data for order
* @return TakerFillResults 0x fill order structs
*/
function fillZeroExOrder(
ZeroExOrder.Order memory _order,
bytes memory _signature,
OrderHandler.OrderHeader memory _header
)
private
returns (address, uint256)
{
// Ensure the taker token is allowed to be transferred by ZeroEx Proxy
address takerToken = OrderHandler.parseERC20TokenAddress(_order.takerAssetData);
ERC20.ensureAllowance(
takerToken,
address(this),
zeroExProxy,
_order.takerAssetAmount
);
ZeroExFillResults.FillResults memory fillResults = ZeroExExchange(zeroExExchange).fillOrKillOrder(
_order,
_header.fillAmount,
_signature
);
// Ensure the maker token is allowed to be transferred by Set TransferProxy
address makerToken = OrderHandler.parseERC20TokenAddress(_order.makerAssetData);
ERC20.ensureAllowance(
makerToken,
address(this),
setTransferProxy,
_order.makerAssetAmount
);
return (
makerToken,
fillResults.makerAssetFilledAmount
);
}
}
| ============ State Variables ============ */ ============ Constructor ============ */* Initialize exchange wrapper with required addresses to facilitate 0x orders @param _zeroExExchange 0x Exchange contract for filling orders @param _zeroExProxy 0x Proxy contract for transferring @param _setTransferProxy Set Protocol transfer proxy contract/ | {
zeroExExchange = _zeroExExchange;
zeroExProxy = _zeroExProxy;
setTransferProxy = _setTransferProxy;
}
| 15,799,347 | [
1,
14468,
3287,
23536,
422,
1432,
631,
342,
422,
1432,
631,
11417,
422,
1432,
631,
342,
9190,
7829,
4053,
598,
1931,
6138,
358,
5853,
330,
305,
340,
374,
92,
11077,
282,
389,
7124,
424,
11688,
377,
374,
92,
18903,
6835,
364,
25740,
11077,
282,
389,
7124,
424,
3886,
3639,
374,
92,
7659,
6835,
364,
906,
74,
20245,
282,
389,
542,
5912,
3886,
282,
1000,
4547,
7412,
2889,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
3634,
424,
11688,
273,
389,
7124,
424,
11688,
31,
203,
3639,
3634,
424,
3886,
273,
389,
7124,
424,
3886,
31,
203,
3639,
444,
5912,
3886,
273,
389,
542,
5912,
3886,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-01
*/
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
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.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
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.6.8;
/**
* @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 EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// 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.
// This means that we can only create new EnumMaps 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
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map.entries.push(MapEntry({key: key, value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map.indexes[key] = map.entries.length;
return true;
} else {
map.entries[keyIndex - 1].value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Map storage map, bytes32 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map.entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map.entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map.entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map.entries.pop();
// Delete the index for the deleted slot
delete map.indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Map storage map, bytes32 key) internal 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) internal 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) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: 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) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
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.6.8;
/**
* @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 EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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 @animoca/ethereum-contracts-core_library-5.0.0/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable {
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "Payout: zero address");
require(payoutWallet_ != address(this), "Payout: this contract as payout");
require(payoutWallet_ != payoutWallet, "Payout: same payout wallet");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor() internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <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 {
/**
* @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/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts/math/[email protected]
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;
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after
* each purchase. If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param extData Implementation-specific extra purchase data, such as
* details about discounts applied, conversion rates, purchase receipts, etc.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes extData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
// solhint-disable-next-line func-name-mixedcase
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
// solhint-disable-next-line func-name-mixedcase
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256(
* "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) {
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title Sale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
// solhint-disable-next-line reason-string
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable virtual override whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
override
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
require(totalSupply != 0, "Sale: non-existent sku");
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view override returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function _createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) internal virtual {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Updates SKU token prices.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @param tokenPrices Storage pointer to a mapping of SKU token prices to update.
* @param tokens The list of payment tokens to update.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.token` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual override {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.token != address(0), "Sale: zero address token");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
bytes32 priceKey = bytes32(uint256(purchase.token));
require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token");
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData)
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An Sale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is Sale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual override {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed");
}
}
/* Internal Utility Functions */
/**
* Retrieves the unit price of a SKU for the specified payment token.
* @dev Reverts if the specified payment token is unsupported.
* @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved.
* @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from.
* @return unitPrice The unit price of a SKU for the specified payment token.
*/
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) {
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File contracts/solc-0.6/sale/GAMEEVoucherSale.sol
pragma solidity 0.6.8;
/**
* @title GAMEEVoucherSale
* A FixedPricesSale contract implementation that handles the purchase of pre-minted GAMEE token
* (GMEE) voucher fungible tokens from a holder account to the purchase recipient.
*/
contract GAMEEVoucherSale is FixedPricesSale {
IGAMEEVoucherInventoryTransferable public immutable inventory;
address public immutable tokenHolder;
mapping(bytes32 => uint256) public skuTokenIds;
/**
* Constructor.
* @dev Reverts if `inventory_` is the zero address.
* @dev Reverts if `tokenHolder_` is the zero address.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param inventory_ The inventory contract from which the sale supply is attributed from.
* @param tokenHolder_ The account holding the pool of sale supply tokens.
* @param payoutWallet the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address inventory_,
address tokenHolder_,
address payoutWallet,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) public FixedPricesSale(payoutWallet, skusCapacity, tokensPerSkuCapacity) {
// solhint-disable-next-line reason-string
require(inventory_ != address(0), "GAMEEVoucherSale: zero address inventory");
// solhint-disable-next-line reason-string
require(tokenHolder_ != address(0), "GAMEEVoucherSale: zero address token holder");
inventory = IGAMEEVoucherInventoryTransferable(inventory_);
tokenHolder = tokenHolder_;
}
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Reverts if `tokenId` is zero.
* @dev Emits the `SkuCreation` event.
* @param sku The SKU identifier.
* @param totalSupply The initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
* @param tokenId The inventory contract token ID to associate with the SKU, used for purchase
* delivery.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
uint256 tokenId
) external onlyOwner whenPaused {
require(tokenId != 0, "GAMEEVoucherSale: zero token ID");
_createSku(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
skuTokenIds[sku] = tokenId;
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal override {
super._delivery(purchase);
inventory.safeTransferFrom(tokenHolder, purchase.recipient, skuTokenIds[purchase.sku], purchase.quantity, "");
}
}
/**
* @dev Interface for the transfer function of the GAMEE voucher inventory contract.
*/
interface IGAMEEVoucherInventoryTransferable {
/**
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits a `TransferSingle` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
} | * @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) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
| 2,027,138 | [
1,
1356,
326,
498,
17,
1132,
3082,
4041,
622,
1754,
1375,
1615,
68,
316,
326,
852,
18,
531,
12,
21,
2934,
3609,
716,
1915,
854,
1158,
28790,
603,
326,
9543,
434,
3222,
4832,
326,
526,
16,
471,
518,
2026,
2549,
1347,
1898,
3222,
854,
3096,
578,
3723,
18,
29076,
30,
300,
1375,
1615,
68,
1297,
506,
23457,
5242,
2353,
288,
2469,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
622,
12,
863,
2502,
852,
16,
2254,
5034,
770,
13,
2713,
1476,
1135,
261,
3890,
1578,
16,
1731,
1578,
13,
288,
203,
3639,
2583,
12,
1458,
18,
8219,
18,
2469,
405,
770,
16,
315,
3572,
863,
30,
770,
596,
434,
4972,
8863,
203,
203,
3639,
1635,
1622,
2502,
1241,
273,
852,
18,
8219,
63,
1615,
15533,
203,
3639,
327,
261,
4099,
18,
856,
16,
1241,
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
] |
/*
*
*
* ;'+:
* ''''''`
* ''''''';
* ''''''''+.
* +''''''''',
* '''''''''+'.
* ''''''''''''
* '''''''''''''
* ,'''''''''''''.
* '''''''''''''''
* '''''''''''''''
* :'''''''''''''''.
* '''''''''''''''';
* .'''''''''''''''''
* ''''''''''''''''''
* ;''''''''''''''''''
* '''''''''''''''''+'
* ''''''''''''''''''''
* '''''''''''''''''''',
* ,''''''''''''''''''''
* '''''''''''''''''''''
* ''''''''''''''''''''':
* ''''''''''''''''''''+'
* `''''''''''''''''''''':
* ''''''''''''''''''''''
* .''''''''''''''''''''';
* ''''''''''''''''''''''`
* ''''''''''''''''''''''
* ''''''''''''''''''''''
* : ''''''''''''''''''''''
* ,: ''''''''''''''''''''''
* :::. ''+''''''''''''''''''':
* ,:,,:` .:::::::,. :''''''''''''''''''''''.
* ,,,::::,.,::::::::,:::,::,''''''''''''''''''''''';
* :::::::,::,::::::::,,,''''''''''''''''''''''''''''''`
* :::::::::,::::::::;'''''''''''''''''''''''''''''''''+`
* ,:,::::::::::::,;''''''''''''''''''''''''''''''''''''';
* :,,:::::::::::'''''''''''''''''''''''''''''''''''''''''
* ::::::::::,''''''''''''''''''''''''''''''''''''''''''''
* :,,:,:,:''''''''''''''''''''''''''''''''''''''''''''''`
* .;::;'''''''''''''''''''''''''''''''''''''''''''''''''
* :'+'''''''''''''''''''''''''''''''''''''''''''''''
* ``.::;'''''''''''''';;:::,..`````,'''''''''',
* ''''''';
* ''''''
* .'''''''; ''''''''''''' '''''''' '''''
* '''''''''''` ''''''''''''' ;''''''''''; ''';
* ''' '''` '' ''', ,''' '':
* ''' : '' `'' ''` :'`
* '' '' '': :'' '
* '' '''''''''' '' '' '
* `'' ''''''''' '''''''''' '' ''
* '' '''''''': '' '' ''
* '' '' '' ''' '''
* ''' ''' '' ''' '''
* '''. .''' '' '''. .'''
* `'''''''''' '''''''''''''` `''''''''''
* ''''''' '''''''''''''` .''''''.
*
*/
pragma solidity ^0.4.26;
// ---------------------------------------------------------------------------------------------
// 'Debit Coin Tokens' ERC20 Token
//
// Deployed to : GeoCredits.Eth
// Symbol : GEO
// Name : Geo Credits Token
// Total supply: Fractional Mint
// Decimals : 4
//
// (c) by A. Valamontes with Blockchain Ventures / Geopay.me Inc 2013-2019. Affero GPLv3 Licence.
// ----------------------------------------------------------------------------------------------
contract SafeMath {
constructor() internal {
}
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public pure returns (address) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned {
constructor() public {
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// since v0.4.12 of compiler we need this
modifier validAddressForSecond(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddressForSecond(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function allowance(address _owner, address _spender) public pure returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is IERC20Token, SafeMath {
string public standard = 'Token 0.1';
string public name = 'DEBIT Coin Token';
string public symbol = 'DBC';
uint8 public decimals = 8;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(string _name, string _symbol, uint8 _decimals) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// since v0.4.12 compiler we need this
modifier validAddressForSecond(address _address) {
require(_address != 0x0);
_;
}
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddressForSecond(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
contract IDebitCoinToken is ITokenHolder, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract DebitCoinToken is IDebitCoinToken, ERC20Token, Owned, TokenHolder {
string public version = '0.2';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
uint public MiningRewardPerETHBlock = 5; // define amount of reaward in DEBITCoin, for miner that found last block in Ethereum BlockChain
uint public lastBlockRewarded;
// triggered when a DEBITCoin token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event DebitCoinTokenGenesis(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
// triggered when the amount of reaward for mining are changesd
event MiningRewardChanged(uint256 _amount);
// triggered when miner get a reward
event MiningRewardSent(address indexed _from, address indexed _to, uint256 _value);
constructor(string _name, string _symbol, uint8 _decimals)
ERC20Token(_name, _symbol, _decimals) public
{
require(bytes(_symbol).length <= 6); // validate input
emit DebitCoinTokenGenesis(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
function TransferMinersReward() public {
require(lastBlockRewarded < block.number);
lastBlockRewarded = block.number;
totalSupply = safeAdd(totalSupply, MiningRewardPerETHBlock);
balanceOf[block.coinbase] = safeAdd(balanceOf[block.coinbase], MiningRewardPerETHBlock);
emit MiningRewardSent(this, block.coinbase, MiningRewardPerETHBlock);
}
function ChangeMiningReward(uint256 _amount) public ownerOnly {
MiningRewardPerETHBlock = _amount;
emit MiningRewardChanged(_amount);
}
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
emit Issuance(_amount);
emit Transfer(this, _to, _amount);
}
function destroy(address _from, uint256 _amount)
public
ownerOnly
{
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
emit Transfer(_from, this, _amount);
emit Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
emit Destruction(_value);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
emit Destruction(_value);
}
return true;
}
}
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
uint public originalSupply;
/** Interface marker */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*/
contract UpgradeableToken is DebitCoinToken {
/** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint256 public totalUpgraded;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can bgun
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value);
// Take tokens out from circulation
totalSupply = safeSub(totalSupply, value);
totalUpgraded = safeAdd(totalUpgraded, value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
emit Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles
*/
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != 0x0);
// Only a master can designate the next agent
require(msg.sender == upgradeMaster);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply);
emit UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address master) public {
require(master != 0x0);
require(msg.sender == upgradeMaster);
upgradeMaster = master;
}
/**
* Child contract can enable to provide the condition when the upgrade can begun.
*/
function canUpgrade() public pure returns(bool) {
return true;
}
}
// (c) by A. Valamontes with Blockchain Ventures / Geopay.me Inc 2013-2019. Affero GPLv3 Licence.
// ---------------------------------------------------------------------------------------------- | these functions aren't abstract since the compiler emits automatically generated getter functions as external | contract IERC20Token {
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 pure returns (uint256 remaining) { _owner; _spender; remaining; }
}
| 6,466,872 | [
1,
451,
3392,
4186,
11526,
1404,
8770,
3241,
326,
5274,
24169,
6635,
4374,
7060,
4186,
487,
3903,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
467,
654,
39,
3462,
1345,
288,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
565,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
16618,
1135,
261,
11890,
5034,
4463,
13,
288,
389,
8443,
31,
389,
87,
1302,
264,
31,
4463,
31,
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
] |
//SPDX-License-Identifier: mit
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Wrapper {
ERC20 private inToken;
constructor(address _inToken) {
inToken = ERC20(_inToken);
}
/**
* Convert an amount of input token_ to an equivalent amount of the output token
*
* @param token_ address of token to swap
* @param amount amount of token to swap/receive
*/
function swap(address token_, uint amount) external {
require(ERC20(token_).transferFrom(msg.sender, address(this), amount));
require(inToken.transfer(msg.sender, amount));
}
/**
* Convert an amount of the output token to an equivalent amount of input token_
*
* @param token_ address of token to receive
* @param amount amount of token to swap/receive
*/
function unswap(address token_, uint amount) external {
require(inToken.transferFrom(msg.sender, address(this), amount));
require(ERC20(token_).transfer(msg.sender, amount));
}
}
| * Convert an amount of the output token to an equivalent amount of input token_ @param token_ address of token to receive @param amount amount of token to swap/receive/ | function unswap(address token_, uint amount) external {
require(inToken.transferFrom(msg.sender, address(this), amount));
require(ERC20(token_).transfer(msg.sender, amount));
}
| 12,633,259 | [
1,
2723,
392,
3844,
434,
326,
876,
1147,
358,
392,
7680,
3844,
434,
810,
1147,
67,
225,
1147,
67,
1758,
434,
1147,
358,
6798,
225,
3844,
3844,
434,
1147,
358,
7720,
19,
18149,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
640,
22270,
12,
2867,
1147,
67,
16,
2254,
3844,
13,
3903,
288,
203,
3639,
2583,
12,
267,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
10019,
203,
3639,
2583,
12,
654,
39,
3462,
12,
2316,
67,
2934,
13866,
12,
3576,
18,
15330,
16,
3844,
10019,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.26;
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract PIG is SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public freezeOf;
mapping(address => mapping(address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function PIG(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply;
// Give the creator all initial tokens
totalSupply = initialSupply * 10 ** uint256(decimals);
// Update total supply
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
decimals = decimalUnits;
// Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw;
// Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
Transfer(msg.sender, _to, _value);
// Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw;
// Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
if (_value > allowance[_from][msg.sender]) throw;
// Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply, _value);
// Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value);
// Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value);
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if (msg.sender != owner) throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
} | Check if the sender has enough Subtract from the sender Updates totalSupply | function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
totalSupply = SafeMath.safeSub(totalSupply, _value);
Burn(msg.sender, _value);
return true;
}
| 13,537,236 | [
1,
1564,
309,
326,
5793,
711,
7304,
2592,
1575,
628,
326,
5793,
15419,
2078,
3088,
1283,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18305,
12,
11890,
5034,
389,
1132,
13,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
309,
261,
12296,
951,
63,
3576,
18,
15330,
65,
411,
389,
1132,
13,
604,
31,
203,
3639,
309,
261,
67,
1132,
1648,
374,
13,
604,
31,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
14060,
10477,
18,
4626,
1676,
12,
12296,
951,
63,
3576,
18,
15330,
6487,
389,
1132,
1769,
203,
3639,
2078,
3088,
1283,
273,
14060,
10477,
18,
4626,
1676,
12,
4963,
3088,
1283,
16,
389,
1132,
1769,
203,
3639,
605,
321,
12,
3576,
18,
15330,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-11-08
*/
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 GTXGCoin 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 = "GTXGCoin";
symbol = "GXTX";
decimals = 3;
_totalSupply = 21000000000;
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 = "GTXGCoin";
symbol = "GXTX";
decimals = 3;
_totalSupply = 21000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 6,685,791 | [
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,
16506,
60,
15396,
885,
14432,
203,
3639,
3273,
273,
315,
43,
3983,
60,
14432,
203,
3639,
15105,
273,
890,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
9035,
2787,
11706,
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,
-100,
-100,
-100
] |
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol";
import { ICErc20 } from "../interfaces/ICErc20.sol";
import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol";
import { IFLIStrategyAdapter } from "../interfaces/IFLIStrategyAdapter.sol";
import { IUniswapV2Router } from "../interfaces/IUniswapV2Router.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
/**
* @title FLIRebalanceViewer
* @author Set Protocol
*
* FLI Rebalance viewer that returns whether a Compound oracle update should be forced before a rebalance goes through, if no
* oracle update the type of rebalance transaction will be returned adhering to the enum specified in FlexibleLeverageStrategyAdapter
*
* CHANGELOG: 4/28/2021
* - Enables calculating Uniswap price with any multihop route
* - Lever and delever exchange data is read directly from strategy adapter and if not empty, calculate price based on encoded route
*/
contract FLIRebalanceViewer {
using PreciseUnitMath for uint256;
using SafeMath for uint256;
/* ============ Enums ============ */
enum FLIRebalanceAction {
NONE, // Indicates no rebalance action can be taken
REBALANCE, // Indicates rebalance() function can be successfully called
ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called
RIPCORD, // Indicates ripcord() function can be successfully called
ORACLE // Indicates Compound oracle update should be pushed
}
/* ============ State Variables ============ */
IUniswapV2Router public uniswapRouter;
IFLIStrategyAdapter public strategyAdapter;
address public cEther;
/* ============ Constructor ============ */
constructor(IUniswapV2Router _uniswapRouter, IFLIStrategyAdapter _strategyAdapter, address _cEther) public {
uniswapRouter = _uniswapRouter;
strategyAdapter = _strategyAdapter;
cEther = _cEther;
}
/* ============ External Functions ============ */
/**
* Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the
* logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with
* 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord(). Additionally, logic is added to check if an oracle update
* should be forced to the Compound protocol ahead of the rebalance (4).
*
* @param _customMinLeverageRatio Min leverage ratio passed in by caller to trigger rebalance
* @param _customMaxLeverageRatio Max leverage ratio passed in by caller to trigger rebalance
*
* return FLIRebalanceAction Enum detailing whether to do nothing, rebalance, iterateRebalance, ripcord, or update Compound oracle
*/
function shouldRebalanceWithBounds(
uint256 _customMinLeverageRatio,
uint256 _customMaxLeverageRatio
)
external
view
returns(FLIRebalanceAction)
{
FlexibleLeverageStrategyAdapter.ShouldRebalance adapterRebalanceState = strategyAdapter.shouldRebalanceWithBounds(
_customMinLeverageRatio,
_customMaxLeverageRatio
);
if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.NONE) {
return FLIRebalanceAction.NONE;
} else if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.RIPCORD) {
FlexibleLeverageStrategyAdapter.IncentiveSettings memory incentive = strategyAdapter.getIncentive();
bool updateOracle = _shouldOracleBeUpdated(incentive.incentivizedTwapMaxTradeSize, incentive.incentivizedSlippageTolerance);
return updateOracle ? FLIRebalanceAction.ORACLE : FLIRebalanceAction.RIPCORD;
} else {
FlexibleLeverageStrategyAdapter.ExecutionSettings memory execution = strategyAdapter.getExecution();
FLIRebalanceAction rebalanceAction = adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.REBALANCE ?
FLIRebalanceAction.REBALANCE : FLIRebalanceAction.ITERATE_REBALANCE;
bool updateOracle = _shouldOracleBeUpdated(execution.twapMaxTradeSize, execution.slippageTolerance);
return updateOracle ? FLIRebalanceAction.ORACLE : rebalanceAction;
}
}
/* ============ Internal Functions ============ */
/**
* Checks if the Compound oracles should be updated before executing any rebalance action. Updates must occur if the resulting trade would end up outside the
* slippage bounds as calculated against the Compound oracle. Aligning the oracle more closely with market prices should allow rebalances to go through.
*
* @param _maxTradeSize Max trade size of rebalance action (varies whether its ripcord or normal rebalance)
* @param _slippageTolerance Slippage tolerance of rebalance action (varies whether its ripcord or normal rebalance)
*
* return bool Boolean indicating whether oracle needs to be updated
*/
function _shouldOracleBeUpdated(
uint256 _maxTradeSize,
uint256 _slippageTolerance
)
internal
view
returns (bool)
{
FlexibleLeverageStrategyAdapter.ContractSettings memory settings = strategyAdapter.getStrategy();
uint256 executionPrice;
uint256 oraclePrice;
if (strategyAdapter.getCurrentLeverageRatio() > strategyAdapter.getMethodology().targetLeverageRatio) {
executionPrice = _getUniswapExecutionPrice(settings.borrowAsset, settings.collateralAsset, _maxTradeSize, false);
oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetBorrowCToken, settings.targetCollateralCToken);
} else {
executionPrice = _getUniswapExecutionPrice(settings.collateralAsset, settings.borrowAsset, _maxTradeSize, true);
oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetCollateralCToken, settings.targetBorrowCToken);
}
return executionPrice > oraclePrice.preciseMul(PreciseUnitMath.preciseUnit().add(_slippageTolerance));
}
/**
* Calculates Uniswap exection price by querying Uniswap for expected token flow amounts for a trade and implying market price. Returned value
* is normalized to 18 decimals.
*
* @param _buyAsset Asset being bought on Uniswap
* @param _sellAsset Asset being sold on Uniswap
* @param _tradeSize Size of the trade in collateral units
* @param _isBuyingCollateral Whether collateral is being bought or sold (used to determine which Uniswap function to call)
*
* return uint256 Implied Uniswap market price for pair, normalized to 18 decimals
*/
function _getUniswapExecutionPrice(
address _buyAsset,
address _sellAsset,
uint256 _tradeSize,
bool _isBuyingCollateral
)
internal
view
returns (uint256)
{
bytes memory pathCalldata = _isBuyingCollateral ? strategyAdapter.getExecution().leverExchangeData : strategyAdapter.getExecution().deleverExchangeData;
address[] memory path;
if(pathCalldata.length == 0){
path = new address[](2);
path[0] = _sellAsset;
path[1] = _buyAsset;
} else {
path = abi.decode(pathCalldata, (address[]));
}
// Returned [sellAmount, buyAmount]
uint256[] memory flows = _isBuyingCollateral ? uniswapRouter.getAmountsIn(_tradeSize, path) : uniswapRouter.getAmountsOut(_tradeSize, path);
uint256 buyDecimals = uint256(10)**ERC20(_buyAsset).decimals();
uint256 sellDecimals = uint256(10)**ERC20(_sellAsset).decimals();
uint256 lastIndex = path.length.sub(1);
return flows[0].preciseDiv(sellDecimals).preciseDiv(flows[lastIndex].preciseDiv(buyDecimals));
}
/**
* Calculates Compound oracle price
*
* @param _priceOracle Compound price oracle
* @param _cTokenBuyAsset CToken having net exposure increased (ie if net balance is short, decreasing short)
* @param _cTokenSellAsset CToken having net exposure decreased (ie if net balance is short, increasing short)
*
* return uint256 Compound oracle price for pair, normalized to 18 decimals
*/
function _getCompoundOraclePrice(
ICompoundPriceOracle _priceOracle,
ICErc20 _cTokenBuyAsset,
ICErc20 _cTokenSellAsset
)
internal
view
returns (uint256)
{
uint256 buyPrice = _priceOracle.getUnderlyingPrice(address(_cTokenBuyAsset));
uint256 sellPrice = _priceOracle.getUnderlyingPrice(address(_cTokenSellAsset));
uint256 buyDecimals = address(_cTokenBuyAsset) == cEther ?
PreciseUnitMath.preciseUnit() :
uint256(10)**ERC20(_cTokenBuyAsset.underlying()).decimals();
uint256 sellDecimals = address(_cTokenSellAsset) == cEther ?
PreciseUnitMath.preciseUnit() :
uint256(10)**ERC20(_cTokenSellAsset.underlying()).decimals();
return buyPrice.mul(buyDecimals).preciseDiv(sellPrice.mul(sellDecimals));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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;
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { BaseAdapter } from "../lib/BaseAdapter.sol";
import { ICErc20 } from "../interfaces/ICErc20.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
import { IComptroller } from "../interfaces/IComptroller.sol";
import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol";
import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
/**
* @title FlexibleLeverageStrategyAdapter
* @author Set Protocol
*
* Smart contract that enables trustless leverage tokens using the flexible leverage methodology. This adapter is paired with the CompoundLeverageModule from Set
* protocol where module interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow
* asset is available on Compound. This adapter contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance function at
* different leverage thresholds.
*
* CHANGELOG 4/14/2021:
* - Update ExecutionSettings struct to split exchangeData into leverExchangeData and deleverExchangeData
* - Update _lever and _delever internal functions with struct changes
* - Update setExecutionSettings to account for leverExchangeData and deleverExchangeData
*/
contract FlexibleLeverageStrategyAdapter is BaseAdapter {
using Address for address;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
/* ============ Enums ============ */
enum ShouldRebalance {
NONE, // Indicates no rebalance action can be taken
REBALANCE, // Indicates rebalance() function can be successfully called
ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called
RIPCORD // Indicates ripcord() function can be successfully called
}
/* ============ Structs ============ */
struct ActionInfo {
uint256 collateralPrice; // Price of underlying in precise units (10e18)
uint256 borrowPrice; // Price of underlying in precise units (10e18)
uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6)
uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units
uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18)
uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18)
uint256 setTotalSupply; // Total supply of SetToken
}
struct LeverageInfo {
ActionInfo action;
uint256 currentLeverageRatio; // Current leverage ratio of Set
uint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16)
uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance action
}
struct ContractSettings {
ISetToken setToken; // Instance of leverage token
ICompoundLeverageModule leverageModule; // Instance of Compound leverage module
IComptroller comptroller; // Instance of Compound Comptroller
ICompoundPriceOracle priceOracle; // Compound open oracle feed that returns prices accounting for decimals. e.g. USDC 6 decimals = 10^18 * 10^18 / 10^6
ICErc20 targetCollateralCToken; // Instance of target collateral cToken asset
ICErc20 targetBorrowCToken; // Instance of target borrow cToken asset
address collateralAsset; // Address of underlying collateral
address borrowAsset; // Address of underlying borrow asset
}
struct MethodologySettings {
uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18)
uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratio
uint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratio
uint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18)
uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds
}
struct ExecutionSettings {
uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16)
uint256 twapMaxTradeSize; // Max trade size in collateral base units
uint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds
uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantities
string exchangeName; // Name of exchange that is being used for leverage
bytes leverExchangeData; // Arbitrary exchange data passed into rebalance function for levering up
bytes deleverExchangeData; // Arbitrary exchange data passed into rebalance function for delevering
}
struct IncentiveSettings {
uint256 etherReward; // ETH reward for incentivized rebalances
uint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalances
uint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalances
uint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances
uint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base units
}
/* ============ Events ============ */
event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
event Rebalanced(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
event RebalanceIterated(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
event RipcordCalled(
uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _rebalanceNotional,
uint256 _etherIncentive
);
event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
event MethodologySettingsUpdated(
uint256 _targetLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio,
uint256 _recenteringSpeed,
uint256 _rebalanceInterval
);
event ExecutionSettingsUpdated(
uint256 _unutilizedLeveragePercentage,
uint256 _twapMaxTradeSize,
uint256 _twapCooldownPeriod,
uint256 _slippageTolerance,
string _exchangeName,
bytes _leverExchangeData,
bytes _deleverExchangeData
);
event IncentiveSettingsUpdated(
uint256 _etherReward,
uint256 _incentivizedLeverageRatio,
uint256 _incentivizedSlippageTolerance,
uint256 _incentivizedTwapCooldownPeriod,
uint256 _incentivizedTwapMaxTradeSize
);
/* ============ Modifiers ============ */
/**
* Throws if rebalance is currently in TWAP`
*/
modifier noRebalanceInProgress() {
require(twapLeverageRatio == 0, "Rebalance is currently in progress");
_;
}
/* ============ State Variables ============ */
ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc)
MethodologySettings internal methodology; // Struct containing methodology parameters
ExecutionSettings internal execution; // Struct containing execution parameters
IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcord
uint256 public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalances
uint256 public lastTradeTimestamp; // Last rebalance timestamp. Must be past rebalance interval to rebalance
/* ============ Constructor ============ */
/**
* Instantiate addresses, methodology parameters, execution parameters, and incentive parameters.
*
* @param _manager Address of IBaseManager contract
* @param _strategy Struct of contract addresses
* @param _methodology Struct containing methodology parameters
* @param _execution Struct containing execution parameters
* @param _incentive Struct containing incentive parameters for ripcord
*/
constructor(
IBaseManager _manager,
ContractSettings memory _strategy,
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive
)
public
BaseAdapter(_manager)
{
strategy = _strategy;
methodology = _methodology;
execution = _execution;
incentive = _incentive;
_validateSettings(methodology, execution, incentive);
}
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Compound and trade for collateral asset. If target
* leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target
* is met.
*/
function engage() external onlyOperator {
ActionInfo memory engageInfo = _createActionInfo();
require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0");
require(engageInfo.borrowBalance == 0, "Debt must be 0");
LeverageInfo memory leverageInfo = LeverageInfo({
action: engageInfo,
currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units
slippageTolerance: execution.slippageTolerance,
twapMaxTradeSize: execution.twapMaxTradeSize
});
// Calculate total rebalance units and kick off TWAP if above max borrow or max trade size
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true);
_lever(leverageInfo, chunkRebalanceNotional);
_updateRebalanceState(
chunkRebalanceNotional,
totalRebalanceNotional,
methodology.targetLeverageRatio
);
emit Engaged(
leverageInfo.currentLeverageRatio,
methodology.targetLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Rebalance according to flexible leverage methodology. If current leverage ratio is between the max and min bounds, then rebalance
* can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage
* ratio back to the max or min bounds. The methodology will determine whether to delever or lever.
*
* Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call
* ripcord() which is incentivized with a reward in Ether or iterateRebalance().
*/
function rebalance() external onlyEOA onlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize);
_validateNormalRebalance(leverageInfo, methodology.rebalanceInterval);
_validateNonTWAP();
uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio);
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _handleRebalance(leverageInfo, newLeverageRatio);
_updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio);
emit Rebalanced(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing
* and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state.
*/
function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize);
_validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod);
_validateTWAP();
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) {
(chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio);
}
// If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is
// cleared
_updateIterateState(chunkRebalanceNotional, totalRebalanceNotional);
emit RebalanceIterated(
leverageInfo.currentLeverageRatio,
twapLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio
* back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller
* of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically
* looser than in regular rebalances.
*/
function ripcord() external onlyEOA {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
incentive.incentivizedSlippageTolerance,
incentive.incentivizedTwapMaxTradeSize
);
_validateRipcord(leverageInfo);
( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false);
_delever(leverageInfo, chunkRebalanceNotional);
_updateRipcordState();
uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward);
emit RipcordCalled(
leverageInfo.currentLeverageRatio,
methodology.maxLeverageRatio,
chunkRebalanceNotional,
etherTransferred
);
}
/**
* OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem
* collateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function will
* delever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator must
* continue to call this function to complete repayment of loan. The function iterateRebalance will not work.
*
* Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch
*/
function disengage() external onlyOperator {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize);
uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);
if (totalRebalanceNotional > chunkRebalanceNotional) {
_delever(leverageInfo, chunkRebalanceNotional);
} else {
_deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
}
emit Disengaged(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newMethodologySettings Struct containing methodology parameters
*/
function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress {
methodology = _newMethodologySettings;
_validateSettings(methodology, execution, incentive);
emit MethodologySettingsUpdated(
methodology.targetLeverageRatio,
methodology.minLeverageRatio,
methodology.maxLeverageRatio,
methodology.recenteringSpeed,
methodology.rebalanceInterval
);
}
/**
* OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newExecutionSettings Struct containing execution parameters
*/
function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress {
execution = _newExecutionSettings;
_validateSettings(methodology, execution, incentive);
emit ExecutionSettingsUpdated(
execution.unutilizedLeveragePercentage,
execution.twapMaxTradeSize,
execution.twapCooldownPeriod,
execution.slippageTolerance,
execution.exchangeName,
execution.leverExchangeData,
execution.deleverExchangeData
);
}
/**
* OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newIncentiveSettings Struct containing incentive parameters
*/
function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress {
incentive = _newIncentiveSettings;
_validateSettings(methodology, execution, incentive);
emit IncentiveSettingsUpdated(
incentive.etherReward,
incentive.incentivizedLeverageRatio,
incentive.incentivizedSlippageTolerance,
incentive.incentivizedTwapCooldownPeriod,
incentive.incentivizedTwapMaxTradeSize
);
}
/**
* OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress
*/
function withdrawEtherBalance() external onlyOperator noRebalanceInProgress {
msg.sender.transfer(address(this).balance);
}
receive() external payable {}
/* ============ External Getter Functions ============ */
/**
* Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral
* and borrow asset are retrieved from the Compound Price Oracle.
*
* return currentLeverageRatio Current leverage ratio in precise units (10e18)
*/
function getCurrentLeverageRatio() public view returns(uint256) {
ActionInfo memory currentLeverageInfo = _createActionInfo();
return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue);
}
/**
* Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is
* below the etherReward, then return the balance of ETH instead.
*
* return etherReward Quantity of ETH reward in base units (10e18)
*/
function getCurrentEtherIncentive() external view returns(uint256) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
// If ETH reward is below the balance on this contract, then return ETH balance on contract instead
return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance;
} else {
return 0;
}
}
/**
* Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()
* 3 = call ripcord()
*
* return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
*/
function shouldRebalance() external view returns(ShouldRebalance) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio);
}
/**
* Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the
* logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with
* 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()3 = call ripcord()
*
* @param _customMinLeverageRatio Min leverage ratio passed in by caller
* @param _customMaxLeverageRatio Max leverage ratio passed in by caller
*
* return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
*/
function shouldRebalanceWithBounds(
uint256 _customMinLeverageRatio,
uint256 _customMaxLeverageRatio
)
external
view
returns(ShouldRebalance)
{
require (
_customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio,
"Custom bounds must be valid"
);
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio);
}
/**
* Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types.
*/
function getStrategy() external view returns (ContractSettings memory) { return strategy; }
function getMethodology() external view returns (MethodologySettings memory) { return methodology; }
function getExecution() external view returns (ExecutionSettings memory) { return execution; }
function getIncentive() external view returns (IncentiveSettings memory) { return incentive; }
/* ============ Internal Functions ============ */
/**
* Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on CompoundLeverageModule
*
*/
function _lever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);
uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance);
bytes memory leverCallData = abi.encodeWithSignature(
"lever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.borrowAsset,
strategy.collateralAsset,
borrowUnits,
minReceiveCollateralUnits,
execution.exchangeName,
execution.leverExchangeData
);
invokeManager(address(strategy.leverageModule), leverCallData);
}
/**
* Calculate delever units Invoke delever on CompoundLeverageModule.
*/
function _delever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action);
bytes memory deleverCallData = abi.encodeWithSignature(
"delever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
collateralRebalanceUnits,
minRepayUnits,
execution.exchangeName,
execution.deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverCallData);
}
/**
* Invoke deleverToZeroBorrowBalance on CompoundLeverageModule.
*/
function _deleverToZeroBorrowBalance(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
// Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function
uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional
.preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance))
.preciseDiv(_leverageInfo.action.setTotalSupply);
bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature(
"deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
maxCollateralRebalanceUnits,
execution.exchangeName,
execution.deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData);
}
/**
* Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions
*
* return uint256 Calculated notional to trade
* return uint256 Total notional to rebalance over TWAP
*/
function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) {
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false);
_delever(_leverageInfo, chunkRebalanceNotional);
} else {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true);
_lever(_leverageInfo, chunkRebalanceNotional);
}
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Create the leverage info struct to be used in internal functions
*
* return LeverageInfo Struct containing ActionInfo and other data
*/
function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) {
ActionInfo memory actionInfo = _createActionInfo();
require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0");
require(actionInfo.borrowBalance > 0, "Borrow balance must exist");
// Get current leverage ratio
uint256 currentLeverageRatio = _calculateCurrentLeverageRatio(
actionInfo.collateralValue,
actionInfo.borrowValue
);
return LeverageInfo({
action: actionInfo,
currentLeverageRatio: currentLeverageRatio,
slippageTolerance: _slippageTolerance,
twapMaxTradeSize: _maxTradeSize
});
}
/**
* Create the action info struct to be used in internal functions
*
* return ActionInfo Struct containing data used by internal lever and delever functions
*/
function _createActionInfo() internal view returns(ActionInfo memory) {
ActionInfo memory rebalanceInfo;
// IMPORTANT: Compound oracle returns prices adjusted for decimals. USDC is 6 decimals so $1 * 10^18 * 10^18 / 10^6 = 10^30
rebalanceInfo.collateralPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetCollateralCToken));
rebalanceInfo.borrowPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetBorrowCToken));
// Calculate stored exchange rate which does not trigger a state update
uint256 cTokenBalance = strategy.targetCollateralCToken.balanceOf(address(strategy.setToken));
rebalanceInfo.collateralBalance = cTokenBalance.preciseMul(strategy.targetCollateralCToken.exchangeRateStored());
rebalanceInfo.borrowBalance = strategy.targetBorrowCToken.borrowBalanceStored(address(strategy.setToken));
rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance);
rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance);
rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply();
return rebalanceInfo;
}
/**
* Validate settings in constructor and setters when updating.
*/
function _validateSettings(
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive
)
internal
pure
{
require (
_methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0,
"Must be valid min leverage"
);
require (
_methodology.maxLeverageRatio >= _methodology.targetLeverageRatio,
"Must be valid max leverage"
);
require (
_methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0,
"Must be valid recentering speed"
);
require (
_execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(),
"Unutilized leverage must be <100%"
);
require (
_execution.slippageTolerance <= PreciseUnitMath.preciseUnit(),
"Slippage tolerance must be <100%"
);
require (
_incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(),
"Incentivized slippage tolerance must be <100%"
);
require (
_incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio,
"Incentivized leverage ratio must be > max leverage ratio"
);
require (
_methodology.rebalanceInterval >= _execution.twapCooldownPeriod,
"Rebalance interval must be greater than TWAP cooldown period"
);
require (
_execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod,
"TWAP cooldown must be greater than incentivized TWAP cooldown"
);
require (
_execution.twapMaxTradeSize <= _incentive.incentivizedTwapMaxTradeSize,
"TWAP max trade size must be less than incentivized TWAP max trade size"
);
}
/**
* Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used
* in rebalance() and iterateRebalance() functions
*/
function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown) internal view {
require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio");
require(
block.timestamp.sub(lastTradeTimestamp) > _coolDown
|| _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio
|| _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio,
"Cooldown not elapsed or not valid leverage ratio"
);
}
/**
* Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord()
*/
function _validateRipcord(LeverageInfo memory _leverageInfo) internal view {
require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio");
// If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed
require(lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed");
}
/**
* Validate TWAP in the iterateRebalance() function
*/
function _validateTWAP() internal view {
require(twapLeverageRatio > 0, "Not in TWAP state");
}
/**
* Validate not TWAP in the rebalance() function
*/
function _validateNonTWAP() internal view {
require(twapLeverageRatio == 0, "Must call iterate");
}
/**
* Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under
* the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance()
*/
function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) {
return (
(twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio)
|| (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio)
);
}
/**
* Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation
*
* return uint256 Current leverage ratio
*/
function _calculateCurrentLeverageRatio(
uint256 _collateralValue,
uint256 _borrowValue
)
internal
pure
returns(uint256)
{
return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue));
}
/**
* Calculate the new leverage ratio using the flexible leverage methodology. The methodology reduces the size of each rebalance by weighting
* the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower
* the leverage token will move towards the target leverage each rebalance.
*
* return uint256 New leverage ratio based on the flexible leverage methodology
*/
function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) {
// CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS))
// a: TLR * RS
// b: (1- RS) * CLRt
// c: (1- RS) * CLRt + TLR * RS
// d: min(MAXLR, CLRt * (1 - RS) + TLR * RS)
uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
uint256 c = a.add(b);
uint256 d = Math.min(c, methodology.maxLeverageRatio);
return Math.max(methodology.minLeverageRatio, d);
}
/**
* Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.
*
* return uint256 Chunked rebalance notional in collateral units
* return uint256 Total rebalance notional in collateral units
*/
function _calculateChunkRebalanceNotional(
LeverageInfo memory _leverageInfo,
uint256 _newLeverageRatio,
bool _isLever
)
internal
view
returns (uint256, uint256)
{
// Calculate absolute value of difference between new and current leverage ratio
uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);
uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);
uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);
uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Calculate the max borrow / repay amount allowed in collateral units for lever / delever. This is due to overcollateralization requirements on
* assets deposited in lending protocols for borrowing.
*
* For lever, max borrow is calculated as:
* (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals
*
* For delever, max borrow is calculated as:
* Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD
*
* Net borrow limit is calculated as:
* The collateral value in USD * Compound collateral factor * (1 - unutilized leverage %)
*
* return uint256 Max borrow notional denominated in collateral asset
*/
function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {
// Retrieve collateral factor which is the % increase in borrow limit in precise units (75% = 75 * 1e16)
( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken));
uint256 netBorrowLimit = _actionInfo.collateralValue
.preciseMul(collateralFactorMantissa)
.preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));
if (_isLever) {
return netBorrowLimit
.sub(_actionInfo.borrowValue)
.preciseDiv(_actionInfo.collateralPrice);
} else {
return _actionInfo.collateralBalance
.preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue))
.preciseDiv(netBorrowLimit);
}
}
/**
* Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price. Compound oracle prices
* already adjust for decimals in the token.
*
* return uint256 Position units to borrow
*/
function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) {
return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice);
}
/**
* Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
*
* return uint256 Min position units to receive after lever trade
*/
function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) {
return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
* and pair price (collateral oracle price / borrow oracle price). Compound oracle prices already adjust for decimals in the token.
*
* return uint256 Min position units to repay in borrow asset
*/
function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) {
return _collateralRebalanceUnits
.preciseMul(_actionInfo.collateralPrice)
.preciseDiv(_actionInfo.borrowPrice)
.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in
* the engage() and rebalance() functions
*/
function _updateRebalanceState(
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional,
uint256 _newLeverageRatio
)
internal
{
lastTradeTimestamp = block.timestamp;
if (_chunkRebalanceNotional < _totalRebalanceNotional) {
twapLeverageRatio = _newLeverageRatio;
}
}
/**
* Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used
* in iterateRebalance()
*/
function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal {
lastTradeTimestamp = block.timestamp;
// If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state.
if (_chunkRebalanceNotional == _totalRebalanceNotional) {
delete twapLeverageRatio;
}
}
/**
* Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function.
*/
function _updateRipcordState() internal {
lastTradeTimestamp = block.timestamp;
// If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the
// incentivized threshold for ripcord.
if (twapLeverageRatio > 0) {
delete twapLeverageRatio;
}
}
/**
* Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required
* incentive quantity, then transfer contract balance instead to prevent reverts.
*
* return uint256 Amount of ETH transferred to caller
*/
function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) {
uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance;
msg.sender.transfer(etherToTransfer);
return etherToTransfer;
}
/**
* Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions
*
* return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
*/
function _shouldRebalance(
uint256 _currentLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio
)
internal
view
returns(ShouldRebalance)
{
// If above ripcord threshold, then check if incentivized cooldown period has elapsed
if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) {
return ShouldRebalance.RIPCORD;
}
} else {
// If TWAP, then check if the cooldown period has elapsed
if (twapLeverageRatio > 0) {
if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) {
return ShouldRebalance.ITERATE_REBALANCE;
}
} else {
// If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below
// min leverage
if (
block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval
|| _currentLeverageRatio > _maxLeverageRatio
|| _currentLeverageRatio < _minLeverageRatio
) {
return ShouldRebalance.REBALANCE;
}
}
}
// If none of the above conditions are satisfied, then should not rebalance
return ShouldRebalance.NONE;
}
}
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ICErc20
*
* Interface for interacting with Compound cErc20 tokens (e.g. Dai, USDC)
*/
interface ICErc20 is IERC20 {
function borrowBalanceCurrent(address _account) external returns (uint256);
function borrowBalanceStored(address _account) external view returns (uint256);
function balanceOfUnderlying(address _account) external returns (uint256);
/**
* Calculates the exchange rate from the underlying to the CToken
*
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external view returns (address);
/**
* Sender supplies assets into the market and receives cTokens in exchange
*
* @notice Accrues interest whether or not the operation succeeds, unless reverted
* @param _mintAmount The amount of the underlying asset to supply
* @return uint256 0=success, otherwise a failure
*/
function mint(uint256 _mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param _redeemTokens The number of cTokens to redeem into underlying
* @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint256 _redeemTokens) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param _redeemAmount The amount of underlying to redeem
* @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint256 _redeemAmount) external returns (uint256);
/**
* @notice Sender borrows assets from the protocol to their own address
* @param _borrowAmount The amount of the underlying asset to borrow
* @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint256 _borrowAmount) external returns (uint256);
/**
* @notice Sender repays their own borrow
* @param _repayAmount The amount to repay
* @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint256 _repayAmount) external returns (uint256);
}
pragma solidity 0.6.10;
/**
* @title ICompoundPriceOracle
*
* Interface for interacting with Compound price oracle
*/
interface ICompoundPriceOracle {
function getUnderlyingPrice(address _asset) external view returns(uint256);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol";
interface IFLIStrategyAdapter {
function getStrategy() external view returns (FlexibleLeverageStrategyAdapter.ContractSettings memory);
function getMethodology() external view returns (FlexibleLeverageStrategyAdapter.MethodologySettings memory);
function getIncentive() external view returns (FlexibleLeverageStrategyAdapter.IncentiveSettings memory);
function getExecution() external view returns (FlexibleLeverageStrategyAdapter.ExecutionSettings memory);
function getCurrentLeverageRatio() external view returns (uint256);
function shouldRebalance() external view returns (FlexibleLeverageStrategyAdapter.ShouldRebalance);
function shouldRebalanceWithBounds(
uint256 _customMinLeverageRatio,
uint256 _customMaxLeverageRatio
)
external
view
returns(FlexibleLeverageStrategyAdapter.ShouldRebalance);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IUniswapV2Router {
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);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
/**
* @title BaseAdapter
* @author Set Protocol
*
* Abstract class that houses common adapter-related state and functions.
*/
abstract contract BaseAdapter {
using AddressArrayUtils for address[];
/* ============ Events ============ */
event CallerStatusUpdated(address indexed _caller, bool _status);
event AnyoneCallableUpdated(bool indexed _status);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == manager.methodologist(), "Must be methodologist");
_;
}
/**
* Throws if caller is a contract, can be used to stop flash loan and sandwich attacks
*/
modifier onlyEOA() {
require(msg.sender == tx.origin, "Caller must be EOA Address");
_;
}
/**
* Throws if not allowed caller
*/
modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
/* ============ State Variables ============ */
// Instance of manager contract
IBaseManager public manager;
// Boolean indicating if anyone can call function
bool public anyoneCallable;
// Mapping of addresses allowed to call function
mapping(address => bool) public callAllowList;
/* ============ Constructor ============ */
constructor(IBaseManager _manager) public { manager = _manager; }
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions
*
* @param _callers Array of caller addresses to toggle status
* @param _statuses Array of statuses for each caller
*/
function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
require(_callers.length == _statuses.length, "Array length mismatch");
require(_callers.length > 0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i = 0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
/**
* OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist
*
* @param _status Boolean indicating whether to allow anyone call
*/
function updateAnyoneCallable(bool _status) external onlyOperator {
anyoneCallable = _status;
emit AnyoneCallableUpdated(_status);
}
/* ============ Internal Functions ============ */
/**
* Invoke manager to transfer tokens from manager to other contract.
*
* @param _token Token being transferred from manager contract
* @param _amount Amount of token being transferred
*/
function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount);
invokeManager(_token, callData);
}
/**
* Invoke call from manager
*
* @param _module Module to interact with
* @param _encoded Encoded byte data
*/
function invokeManager(address _module, bytes memory _encoded) internal {
manager.interactManager(_module, _encoded);
}
/**
* Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved.
*
* return bool Boolean indicating if allowed caller
*/
function isAllowedCaller(address _caller) internal view virtual returns (bool) {
return anyoneCallable || callAllowList[_caller];
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface IBaseManager {
function setToken() external returns(ISetToken);
function methodologist() external returns(address);
function operator() external returns(address);
function interactManager(address _module, bytes calldata _encoded) external;
}
pragma solidity 0.6.10;
/**
* @title IComptroller
*
* Interface for interacting with Compound Comptroller
*/
interface IComptroller {
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing neccessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint256);
function claimComp(address holder) external;
function markets(address cTokenAddress) external view returns (bool, uint256, bool);
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface ICompoundLeverageModule {
function sync(
ISetToken _setToken
) external;
function lever(
ISetToken _setToken,
address _borrowAsset,
address _collateralAsset,
uint256 _borrowQuantity,
uint256 _minReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function delever(
ISetToken _setToken,
address _collateralAsset,
address _repayAsset,
uint256 _redeemQuantity,
uint256 _minRepayQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function gulp(
ISetToken _setToken,
address _collateralAsset,
uint256 _minNotionalReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/27/21: Added validatePairsWithArray methods
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
| * Invoke deleverToZeroBorrowBalance on CompoundLeverageModule./ Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function | function _deleverToZeroBorrowBalance(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal
{
uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional
.preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance))
.preciseDiv(_leverageInfo.action.setTotalSupply);
bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature(
"deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
maxCollateralRebalanceUnits,
execution.exchangeName,
execution.deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData);
}
| 478,761 | [
1,
10969,
1464,
6084,
774,
7170,
38,
15318,
13937,
603,
21327,
1682,
5682,
3120,
18,
19,
6590,
364,
272,
3169,
2433,
10673,
316,
283,
24903,
10457,
364,
326,
1464,
6084,
774,
7170,
38,
15318,
13937,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
3771,
6084,
774,
7170,
38,
15318,
13937,
12,
203,
3639,
3519,
5682,
966,
3778,
389,
298,
5682,
966,
16,
203,
3639,
2254,
5034,
389,
6551,
426,
12296,
1248,
285,
287,
203,
565,
262,
203,
3639,
2713,
203,
565,
288,
203,
3639,
2254,
5034,
943,
13535,
2045,
287,
426,
12296,
7537,
273,
389,
6551,
426,
12296,
1248,
285,
287,
203,
5411,
263,
4036,
784,
27860,
12,
1386,
30708,
2802,
10477,
18,
4036,
784,
2802,
7675,
1289,
12,
16414,
18,
87,
3169,
2433,
22678,
3719,
203,
5411,
263,
4036,
784,
7244,
24899,
298,
5682,
966,
18,
1128,
18,
542,
5269,
3088,
1283,
1769,
203,
203,
3639,
1731,
3778,
1464,
6084,
774,
7170,
38,
15318,
13937,
1477,
751,
273,
24126,
18,
3015,
1190,
5374,
12,
203,
5411,
315,
3771,
6084,
774,
7170,
38,
15318,
13937,
12,
2867,
16,
2867,
16,
2867,
16,
11890,
5034,
16,
1080,
16,
3890,
2225,
16,
203,
5411,
1758,
12,
14914,
18,
542,
1345,
3631,
203,
5411,
6252,
18,
12910,
2045,
287,
6672,
16,
203,
5411,
6252,
18,
70,
15318,
6672,
16,
203,
5411,
943,
13535,
2045,
287,
426,
12296,
7537,
16,
203,
5411,
4588,
18,
16641,
461,
16,
203,
5411,
4588,
18,
3771,
6084,
11688,
751,
203,
3639,
11272,
203,
203,
3639,
4356,
1318,
12,
2867,
12,
14914,
18,
298,
5682,
3120,
3631,
1464,
6084,
774,
7170,
38,
15318,
13937,
1477,
751,
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
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
interface cETH {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// @Uniswap/v2-periphery/blob/master/contracts/interfaces
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
pragma solidity >=0.7.0 <0.9.0;
contract SmartBankUniswap {
uint256 internal contractBalance; // pool ETH in wei
mapping(address => uint256) balances; // user ETH in wei
address COMPOUND_CETH_ADDRESS = 0x859e9d8a4edadfEDb5A2fF311243af80F85A91b8;
cETH ceth = cETH(COMPOUND_CETH_ADDRESS);
address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 uniswap = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
function addBalance() public payable {
balances[msg.sender] += msg.value;
contractBalance += msg.value;
ceth.mint{value: msg.value}();
}
function addBalanceERC20(address erc20Contract) public payable {
uint256 approvedERC20Amount = addtokens(erc20Contract);
uint256 ethAmount = swapTokens(erc20Contract, approvedERC20Amount);
balances[msg.sender] += msg.value;
contractBalance += msg.value;
ceth.mint{value: ethAmount}();
}
function addtokens(address _erc20Contract) internal returns (uint256) {
IERC20 erc20 = IERC20(_erc20Contract);
uint256 approvedERC20Amount = erc20.allowance(
msg.sender,
address(this)
);
erc20.transferFrom(msg.sender, address(this), approvedERC20Amount);
erc20.approve(UNISWAP_ROUTER_ADDRESS, approvedERC20Amount);
return approvedERC20Amount;
}
function swapTokens(address _erc20Contract, uint256 _approvedERC20Amount)
internal
returns (uint256)
{
uint256 amountETHMin = 0; // accept any amount of token
address[] memory path = new address[](2);
path[0] = _erc20Contract;
path[1] = uniswap.WETH(); // check uniswap.exchange
uint256 before = address(this).balance;
uniswap.swapExactTokensForETH(
_approvedERC20Amount,
amountETHMin,
path,
address(this),
block.timestamp + (24 * 60 * 60)
);
uint256 _ethAmount = address(this).balance - before;
return _ethAmount;
}
function withdraw(uint256 withdrawAmount) public payable returns (uint256) {
require(withdrawAmount <= getUserEth(), "overdrawn");
balances[msg.sender] -= msg.value;
contractBalance -= withdrawAmount;
uint256 cethToRedeem = getTotalEthFromCeth() *
(withdrawAmount / contractBalance);
uint256 transferable = ceth.redeem(cethToRedeem);
(bool sent, ) = payable(msg.sender).call{value: transferable}("");
require(sent, "Failed to send Ether");
return transferable;
}
// sanity check
function getAllowanceERC20(address erc20Contract)
public
view
returns (uint256)
{
IERC20 erc20 = IERC20(erc20Contract);
return erc20.allowance(msg.sender, address(this));
}
function getbalanceERC20(address erc20Contract)
public
view
returns (uint256)
{
IERC20 erc20 = IERC20(erc20Contract);
return erc20.balanceOf(address(this));
}
receive() external payable {}
// viewing functions
function getUserEth() public view returns (uint256) {
return (getTotalEthFromCeth() *
(balances[msg.sender] / contractBalance));
}
function getTotalEthFromCeth() public view returns (uint256) {
return ceth.balanceOf(address(this)) * ceth.exchangeRateStored();
}
function getContractBalance() public view returns (uint256) {
return contractBalance;
}
function getExchangeRate() public view returns (uint256) {
return ceth.exchangeRateStored();
}
}
// addresses
// Compound on rinkeby = 0xd6801a1dffcd0a410336ef88def4320d6df1883e
// Compound on ropsten = 0x859e9d8a4edadfedb5a2ff311243af80f85a91b8
// dai on rinkeby = 0xc7ad46e0b8a400bb3c915120d284aafba8fc4735
// dai on ropsten = 0xad6d458402f60fd3bd25163575031acdce07538d
| check uniswap.exchange
| path[1] = uniswap.WETH(); | 15,845,713 | [
1,
1893,
640,
291,
91,
438,
18,
16641,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
589,
63,
21,
65,
273,
640,
291,
91,
438,
18,
59,
1584,
44,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract LivenetErc721Etheremon {
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
);
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 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)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return true;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
emit Approval(address(0), _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return address(0);
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return true;
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
}
// added by etheremon
function transfer(address _to, uint256 _tokenId) external {
emit Transfer(msg.sender, _to, _tokenId);
}
} | * @dev Gets the approved address for a token ID, or zero if no address set @param _tokenId uint256 ID of the token to query the approval of @return address currently approved for the given token ID/ | function getApproved(uint256 _tokenId) public view returns (address) {
return address(0);
}
| 973,575 | [
1,
3002,
326,
20412,
1758,
364,
279,
1147,
1599,
16,
578,
3634,
309,
1158,
1758,
444,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
843,
326,
23556,
434,
327,
1758,
4551,
20412,
364,
326,
864,
1147,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
31639,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
pragma experimental ABIEncoderV2;
contract EncryptedSender {
struct TopicData {
// An (optional) public key used to encrypt messages for this topic. This is only necessary if the sender will
// not have access to the public key offchain.
bytes publicKey;
// The encrypted message.
bytes message;
}
struct Recipient {
// This maps from a hash to the data for this topic.
// Note: the hash is a hash of the "subject" or "topic" of the message.
mapping(bytes32 => TopicData) topics;
// This contains the set of all authorized senders for this recipient.
mapping(address => bool) authorizedSenders;
}
mapping(address => Recipient) private recipients;
/**
* @notice Authorizes `sender` to send messages to the caller.
*/
function addAuthorizedSender(address sender) external {
recipients[msg.sender].authorizedSenders[sender] = true;
}
/**
* @notice Revokes `sender`'s authorization to send messages to the caller.
*/
function removeAuthorizedSender(address sender) external {
recipients[msg.sender].authorizedSenders[sender] = false;
}
/**
* @notice Gets the current stored message corresponding to `recipient` and `topicHash`.
* @dev To decrypt messages (this requires access to the recipient's private keys), use the decryptMessage()
* function in common/Crypto.js.
*/
function getMessage(address recipient, bytes32 topicHash) external view returns (bytes memory) {
return recipients[recipient].topics[topicHash].message;
}
/**
* @notice Gets the stored public key for a particular `recipient` and `topicHash`. Return value will be 0 length
* if no public key has been set.
* @dev Senders may need this public key to encrypt messages that only the `recipient` can read. If the public key
* is communicated offchain, this field may be left empty.
*/
function getPublicKey(address recipient, bytes32 topicHash) external view returns (bytes memory) {
return recipients[recipient].topics[topicHash].publicKey;
}
/**
* @notice Sends `message` to `recipient_` categorized by a particular `topicHash`. This will overwrite any
* previous messages sent to this `recipient` with this `topicHash`.
* @dev To construct an encrypted message, use the encryptMessage() in common/Crypto.js.
* The public key for the recipient can be obtained using the getPublicKey() method.
*/
function sendMessage(address recipient_, bytes32 topicHash, bytes memory message) public {
Recipient storage recipient = recipients[recipient_];
require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to send to this recipient");
recipient.topics[topicHash].message = message;
}
function removeMessage(address recipient_, bytes32 topicHash) public {
Recipient storage recipient = recipients[recipient_];
require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to remove message");
delete recipient.topics[topicHash].message;
}
/**
* @notice Sets the public key for this caller and topicHash.
* @dev Note: setting the public key is optional - if the publicKey is communicated or can be derived offchain by
* the sender, there is no need to set it here. Because there are no specific requirements for the publicKey, there
* is also no verification of its validity other than its length.
*/
function setPublicKey(bytes memory publicKey, bytes32 topicHash) public {
require(publicKey.length == 64, "Public key is the wrong length");
recipients[msg.sender].topics[topicHash].publicKey = publicKey;
}
/**
* @notice Returns true if the `sender` is authorized to send to the `recipient`.
*/
function isAuthorizedSender(address sender, address recipient) public view returns (bool) {
// Note: the recipient is always authorized to send messages to themselves.
return recipients[recipient].authorizedSenders[sender] || recipient == sender;
}
}
library FixedPoint {
using SafeMath for uint;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint 10^77.
uint private constant FP_SCALING_FACTOR = 10**18;
struct Unsigned {
uint rawValue;
}
/** @dev Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. */
function fromUnscaledUint(uint a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(Unsigned memory a, uint b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/** @dev Whether `a` is greater than `b`. */
function isGreaterThan(uint a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(Unsigned memory a, uint b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/** @dev Whether `a` is less than `b`. */
function isLessThan(uint a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/** @dev Adds two `Unsigned`s, reverting on overflow. */
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/** @dev Adds an `Unsigned` to an unscaled uint, reverting on overflow. */
function add(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/** @dev Subtracts two `Unsigned`s, reverting on underflow. */
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/** @dev Subtracts an unscaled uint from an `Unsigned`, reverting on underflow. */
function sub(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/** @dev Subtracts an `Unsigned` from an unscaled uint, reverting on underflow. */
function sub(uint a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/** @dev Multiplies two `Unsigned`s, reverting on overflow. */
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/** @dev Multiplies an `Unsigned` by an unscaled uint, reverting on overflow. */
function mul(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/** @dev Divides with truncation two `Unsigned`s, reverting on overflow or division by 0. */
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/** @dev Divides with truncation an `Unsigned` by an unscaled uint, reverting on division by 0. */
function div(Unsigned memory a, uint b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/** @dev Divides with truncation an unscaled uint by an `Unsigned`, reverting on overflow or division by 0. */
function div(uint a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/** @dev Raises an `Unsigned` to the power of an unscaled uint, reverting on overflow. E.g., `b=2` squares `a`. */
function pow(Unsigned memory a, uint b) internal pure returns (Unsigned memory output) {
// TODO(ptare): Consider using the exponentiation by squaring technique instead:
// https://en.wikipedia.org/wiki/Exponentiation_by_squaring
output = fromUnscaledUint(1);
for (uint i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint => Role) private roles;
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
*/
function holdsRole(uint roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
require(false, "Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, exclusive role.
*/
function resetMember(uint roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
*/
function getMember(uint roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the
* managing role for `roleId`.
*/
function addMember(uint roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the
* managing role for `roleId`.
*/
function removeMember(uint roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(uint roleId, uint managingRoleId, address[] memory initialMembers)
internal
onlyInvalidRole(roleId)
{
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role");
}
/**
* @notice Internal method to initialize a exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(uint roleId, uint managingRoleId, address initialMember)
internal
onlyInvalidRole(roleId)
{
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role");
}
}
interface OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Returns the time at which the user should expect the price to be resolved. 0 means the price has already
* been resolved.
*/
function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime);
/**
* @notice Whether the Oracle provides prices for this identifier.
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
/**
* @notice Whether the price for `identifier` and `time` is available.
*/
function hasPrice(bytes32 identifier, uint time) external view returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
*/
function getPrice(bytes32 identifier, uint time) external view returns (int price);
}
interface RegistryInterface {
/**
* @dev Registers a new derivative. Only authorized derivative creators can call this method.
*/
function registerDerivative(address[] calldata counterparties, address derivativeAddress) external;
/**
* @dev Returns whether the derivative has been registered with the registry (and is therefore an authorized.
* participant in the UMA system).
*/
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered);
/**
* @dev Returns a list of all derivatives that are associated with a particular party.
*/
function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives);
/**
* @dev Returns all registered derivatives.
*/
function getAllRegisteredDerivatives() external view returns (address[] memory derivatives);
}
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint;
enum Roles {
// The owner manages the set of DerivativeCreators.
Owner,
// Can register derivatives.
DerivativeCreator
}
// Array of all derivatives that are approved to use the UMA Oracle.
address[] private registeredDerivatives;
// This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered.
enum PointerValidity {
Invalid,
Valid
}
struct Pointer {
PointerValidity valid;
uint128 index;
}
// Maps from derivative address to a pointer that refers to that registered derivative in `registeredDerivatives`.
mapping(address => Pointer) private derivativePointers;
// Note: this must be stored outside of `registeredDerivatives` because mappings cannot be deleted and copied
// like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose
// of the Pointer struct and break separation of concern between referential data and data.
struct PartiesMap {
mapping(address => bool) parties;
}
// Maps from derivative address to the set of parties that are involved in that derivative.
mapping(address => PartiesMap) private derivativesToParties;
event NewDerivativeRegistered(address indexed derivativeAddress, address indexed creator, address[] parties);
constructor() public {
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
// Start with no derivative creators registered.
_createSharedRole(uint(Roles.DerivativeCreator), uint(Roles.Owner), new address[](0));
}
function registerDerivative(address[] calldata parties, address derivativeAddress)
external
onlyRoleHolder(uint(Roles.DerivativeCreator))
{
// Create derivative pointer.
Pointer storage pointer = derivativePointers[derivativeAddress];
// Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double
// registered).
require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(derivativeAddress);
// No length check necessary because we should never hit (2^127 - 1) derivatives.
pointer.index = uint128(registeredDerivatives.length.sub(1));
// Set up PartiesMap for this derivative.
PartiesMap storage partiesMap = derivativesToParties[derivativeAddress];
for (uint i = 0; i < parties.length; i = i.add(1)) {
partiesMap.parties[parties[i]] = true;
}
address[] memory partiesForEvent = parties;
emit NewDerivativeRegistered(derivativeAddress, msg.sender, partiesForEvent);
}
function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) {
return derivativePointers[derivative].valid == PointerValidity.Valid;
}
function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives) {
// This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long
// as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy
// the array over to the return array, which is allocated using the correct size. Note: this is done by double
// copying each value rather than storing some referential info (like indices) in memory to reduce the number
// of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1).
address[] memory tmpDerivativeArray = new address[](registeredDerivatives.length);
uint outputIndex = 0;
for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) {
address derivative = registeredDerivatives[i];
if (derivativesToParties[derivative].parties[party]) {
// Copy selected derivative to the temporary array.
tmpDerivativeArray[outputIndex] = derivative;
outputIndex = outputIndex.add(1);
}
}
// Copy the temp array to the return array that is set to the correct size.
derivatives = new address[](outputIndex);
for (uint j = 0; j < outputIndex; j = j.add(1)) {
derivatives[j] = tmpDerivativeArray[j];
}
}
function getAllRegisteredDerivatives() external view returns (address[] memory derivatives) {
return registeredDerivatives;
}
}
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int currentMode;
}
/**
* @dev Returns whether the result is resolved, and if so, what value it resolved to. `price` should be ignored if
* `isResolved` is false.
* @param minVoteThreshold Minimum number of tokens that must have been voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int price)
{
// TODO(ptare): Figure out where this parameter is supposed to come from.
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)) {
// `modeThreshold` and `minVoteThreshold` are met, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @dev Adds a new vote to be used when computing the result.
*/
function addVote(Data storage data, int votePrice, FixedPoint.Unsigned memory numberTokens)
internal
{
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (votePrice != data.currentMode
&& data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])) {
data.currentMode = votePrice;
}
}
/**
* @dev Checks whether a `voteHash` is considered correct. Should only be called after a vote is resolved, i.e.,
* via `getResolvedPrice`.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @dev Gets the total number of tokens whose votes are considered correct. Should only be called after a vote is
* resolved, i.e., via `getResolvedPrice`.
*/
function getTotalCorrectlyVotedTokens(Data storage data)
internal
view
returns (FixedPoint.Unsigned memory)
{
return data.voteFrequency[data.currentMode];
}
}
contract Testable {
// Is the contract being run on the test network. Note: this variable should be set on construction and never
// modified.
bool public isTest;
uint private currentTime;
constructor(bool _isTest) internal {
isTest = _isTest;
if (_isTest) {
currentTime = now; // solhint-disable-line not-rely-on-time
}
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(isTest);
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
*/
function setCurrentTime(uint _time) external onlyIfTest {
currentTime = _time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
*/
function getCurrentTime() public view returns (uint) {
if (isTest) {
return currentTime;
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract Governor is MultiRole, Testable {
using SafeMath for uint;
enum Roles {
// Can set the proposer.
Owner,
// Address that can make proposals.
Proposer
}
struct Transaction {
address to;
uint value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint requestTime;
}
Finder private finder;
Proposal[] public proposals;
/**
* @notice Emitted when a new proposal is created.
*/
event NewProposal(uint indexed id, Transaction[] transactions);
/**
* @notice Emitted when an existing proposal is executed.
*/
event ProposalExecuted(uint indexed id, uint transactionIndex);
constructor(address _finderAddress, bool _isTest) public Testable(_isTest) {
finder = Finder(_finderAddress);
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
_createExclusiveRole(uint(Roles.Proposer), uint(Roles.Owner), msg.sender);
}
/**
* @notice Executes a proposed governance action that has been approved by voters. This can be called by anyone.
*/
function executeProposal(uint id, uint transactionIndex) external {
Proposal storage proposal = proposals[id];
int price = _getVoting().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction storage transaction = proposal.transactions[transactionIndex];
require(transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous transaction has not been executed");
require(transaction.to != address(0), "Transaction has already been executed");
require(price != 0, "Cannot execute, proposal was voted down");
require(_executeCall(transaction.to, transaction.value, transaction.data), "Transaction execution failed");
// Delete the transaction.
delete proposal.transactions[transactionIndex];
emit ProposalExecuted(id, transactionIndex);
}
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
*/
function numProposals() external view returns (uint) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* Note: after a proposal is executed, its data will be zeroed out.
*/
function getProposal(uint id) external view returns (Proposal memory proposal) {
return proposals[id];
}
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions the list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that disallows structs arrays to be passed to
* external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint(Roles.Proposer)) {
uint id = proposals.length;
uint time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add an element to the proposals array.
proposals.length = proposals.length.add(1);
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
proposal.transactions.length = transactions.length;
for (uint i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The to address cannot be 0x0");
proposal.transactions[i] = transactions[i];
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
Voting voting = _getVoting();
voting.addSupportedIdentifier(identifier);
// Note: this check is only here to appease slither.
require(voting.requestPrice(identifier, time) != ~uint(0), "Proposal will never be considered");
voting.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
function _constructIdentifier(uint id) private pure returns (bytes32 identifier) {
bytes32 bytesId = _uintToBytes(id);
return _addPrefix(bytesId, "Admin ", 6);
}
function _executeCall(address to, uint256 value, bytes memory data)
private
returns (bool success)
{
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas, to, value, inputData, inputDataSize, 0, 0)
}
}
function _getVoting() private view returns (Voting voting) {
return Voting(finder.getImplementationAddress("Oracle"));
}
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToBytes(uint v) private pure returns (bytes32 ret) {
if (v == 0) {
ret = "0";
} else {
while (v > 0) {
ret = ret >> 8;
ret |= bytes32((v % 10) + 48) << (31 * 8);
v /= 10;
}
}
return ret;
}
function _addPrefix(bytes32 input, bytes32 prefix, uint prefixLength) private pure returns (bytes32 output) {
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
library VoteTiming {
using SafeMath for uint;
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
enum Phase {
Commit,
Reveal
}
// Note: this MUST match the number of values in the enum above.
uint private constant NUM_PHASES = 2;
struct Data {
uint roundId;
uint roundStartTime;
uint phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input and resets the round id and round
* start time to 1 and 0 respectively.
* @dev This method should generally only be run once, but it can also be used to reset the data structure to its
* initial values.
*/
function init(Data storage data, uint phaseLength) internal {
data.phaseLength = phaseLength;
data.roundId = 1;
data.roundStartTime = 0;
}
/**
* @notice Gets the most recently stored round ID set by updateRoundId().
*/
function getLastUpdatedRoundId(Data storage data) internal view returns (uint) {
return data.roundId;
}
/**
* @notice Determines whether time has advanced far enough to advance to the next voting round and update the
* stored round id.
*/
function shouldUpdateRoundId(Data storage data, uint currentTime) internal view returns (bool) {
(uint roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime);
return data.roundId != roundId;
}
/**
* @notice Updates the round id. Note: if shouldUpdateRoundId() returns false, this method will have no effect.
*/
function updateRoundId(Data storage data, uint currentTime) internal {
(data.roundId, data.roundStartTime) = _getCurrentRoundIdAndStartTime(data, currentTime);
}
/**
* @notice Computes what the stored round id would be if it were updated right now, but this method does not
* commit the update.
*/
function computeCurrentRoundId(Data storage data, uint currentTime) internal view returns (uint roundId) {
(roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime);
}
/**
* @notice Computes the current phase based only on the current time.
*/
function computeCurrentPhase(Data storage data, uint currentTime) internal view returns (Phase) {
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return Phase(currentTime.div(data.phaseLength).mod(NUM_PHASES));
}
/**
* @notice Gets the end time of the current round or any round in the future. Note: this method will revert if
* the roundId < getLastUpdatedRoundId().
*/
function computeEstimatedRoundEndTime(Data storage data, uint roundId) internal view returns (uint) {
// The add(1) is because we want the round end time rather than the start time, so it's really the start of
// the next round.
uint roundDiff = roundId.sub(data.roundId).add(1);
uint roundLength = data.phaseLength.mul(NUM_PHASES);
return data.roundStartTime.add(roundDiff.mul(roundLength));
}
/**
* @dev Computes an updated round id and round start time based on the current time.
*/
function _getCurrentRoundIdAndStartTime(Data storage data, uint currentTime)
private
view
returns (uint roundId, uint startTime)
{
uint currentStartTime = data.roundStartTime;
// Return current data if time has moved backwards.
if (currentTime <= data.roundStartTime) {
return (data.roundId, data.roundStartTime);
}
// Get the start of the round that currentTime would be a part of by flooring by roundLength.
uint roundLength = data.phaseLength.mul(NUM_PHASES);
startTime = currentTime.div(roundLength).mul(roundLength);
// Only increment the round ID if the start time has changed.
if (startTime > currentStartTime) {
roundId = data.roundId.add(1);
} else {
roundId = data.roundId;
}
}
}
contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint time;
}
/**
* @notice Commit your vote for a price request for `identifier` at `time`.
* @dev (`identifier`, `time`) must correspond to a price request that's currently in the commit phase. `hash`
* should be the keccak256 hash of the price you want to vote for and a `int salt`. Commits can be changed.
*/
function commitVote(bytes32 identifier, uint time, bytes32 hash) external;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price` and `salt` must match the latest `hash` that `commitVote()` was called with. Only the
* committer can reveal their vote.
*/
function revealVote(bytes32 identifier, uint time, int price, int salt) external;
/**
* @notice Gets the queries that are being voted on this round.
*/
function getPendingRequests() external view returns (PendingRequest[] memory);
/**
* @notice Gets the current vote phase (commit or reveal) based on the current block time.
*/
function getVotePhase() external view returns (VoteTiming.Phase);
/**
* @notice Gets the current vote round id based on the current block time.
*/
function getCurrentRoundId() external view returns (uint);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
*/
function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory) public returns
(FixedPoint.Unsigned memory);
}
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;
}
}
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
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;
}
}
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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Finder is Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @dev Updates the address of the contract that implements `interfaceName`.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @dev Gets the address of the contract that implements the given `interfaceName`.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address implementationAddress)
{
implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "No implementation for interface found");
}
}
contract Voting is Testable, Ownable, OracleInterface, VotingInterface, EncryptedSender {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint time;
// A map containing all votes for this price in various rounds.
mapping(uint => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint index;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint time;
int price;
int salt;
}
struct Round {
// Voting token snapshot ID for this round. If this is 0, no snapshot has been taken.
uint snapshotId;
// Inflation rate set for this round.
FixedPoint.Unsigned inflationRate;
}
// Represents the status a price request has.
enum RequestStatus {
// Was never requested.
NotRequested,
// Is being voted on in the current round.
Active,
// Was resolved in a previous round.
Resolved,
// Is scheduled to be voted on in a future round.
Future
}
// Maps round numbers to the rounds.
mapping(uint => Round) private rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved. These requests may be for future
// rounds.
bytes32[] private pendingPriceRequests;
VoteTiming.Data private voteTiming;
// The set of identifiers the oracle can provide verified prices for.
mapping(bytes32 => bool) private supportedIdentifiers;
// Percentage of the total token supply that must be used in a vote to create a valid price resolution.
// 1 == 100%.
FixedPoint.Unsigned private gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters. Note: this value is used to set per-round inflation at the beginning
// of each round.
// 1 = 100%
FixedPoint.Unsigned private inflationRate;
// Reference to the voting token.
VotingToken private votingToken;
// Reference to the Finder.
Finder private finder;
// If non-zero, this contract has been migrated to this address. All voters and financial contracts should query the
// new address only.
address private migratedAddress;
// Max value of an unsigned integer.
uint constant private UINT_MAX = ~uint(0);
event VoteCommitted(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time);
event VoteRevealed(
address indexed voter,
uint indexed roundId,
bytes32 indexed identifier,
uint time,
int price,
uint numTokens
);
event RewardsRetrieved(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time,
uint numTokens);
event PriceRequestAdded(uint indexed votingRoundId, bytes32 indexed identifier, uint time);
event PriceResolved(uint indexed resolutionRoundId, bytes32 indexed identifier, uint time, int price);
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/**
* @notice Construct the Voting contract.
* @param phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage percentage of the total token supply that must be used in a vote to create a valid price
* resolution.
* @param _isTest whether this contract is being constructed for the purpose of running automated tests.
*/
constructor(
uint phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
address _votingToken,
address _finder,
bool _isTest
) public Testable(_isTest) {
voteTiming.init(phaseLength);
// TODO(#779): GAT percentage must be < 100%
require(_gatPercentage.isLessThan(1));
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = Finder(_finder);
}
modifier onlyRegisteredDerivative() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress);
} else {
Registry registry = Registry(finder.getImplementationAddress("Registry"));
// TODO(#779): Must be registered derivative
require(registry.isDerivativeRegistered(msg.sender));
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0));
_;
}
function requestPrice(bytes32 identifier, uint time)
external
onlyRegisteredDerivative()
returns (uint expectedTime)
{
uint blockTime = getCurrentTime();
// TODO(#779): Price request must be for a time in the past
require(time <= blockTime);
// TODO(#779): Price request for unsupported identifier
require(supportedIdentifiers[identifier]);
// Must ensure the round is updated here so the requested price will be voted on in the next commit cycle.
_updateRound(blockTime);
bytes32 priceRequestId = _encodePriceRequest(identifier, time);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return voteTiming.computeEstimatedRoundEndTime(currentRoundId);
} else if (requestStatus == RequestStatus.Resolved) {
return 0;
} else if (requestStatus == RequestStatus.Future) {
return voteTiming.computeEstimatedRoundEndTime(priceRequest.lastVotingRound);
}
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
// Estimate the end of next round and return the time.
return voteTiming.computeEstimatedRoundEndTime(nextRoundId);
}
function batchCommit(Commitment[] calldata commits) external {
for (uint i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].hash);
} else {
commitAndPersistEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].hash,
commits[i].encryptedVote);
}
}
}
function batchReveal(Reveal[] calldata reveals) external {
for (uint i = 0; i < reveals.length; i++) {
revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt);
}
}
/**
* @notice Disables this Voting contract in favor of the migrated one.
*/
function setMigrated(address newVotingAddress) external onlyOwner {
migratedAddress = newVotingAddress;
}
/**
* @notice Adds the provided identifier as a supported identifier. Price requests using this identifier will be
* succeed after this call.
*/
function addSupportedIdentifier(bytes32 identifier) external onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist. Price requests using this identifier will no longer succeed
* after this call.
*/
function removeSupportedIdentifier(bytes32 identifier) external onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
function isIdentifierSupported(bytes32 identifier) external view returns (bool) {
return supportedIdentifiers[identifier];
}
function hasPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (bool _hasPrice) {
(_hasPrice, ,) = _getPriceOrError(identifier, time);
}
function getPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (int) {
(bool _hasPrice, int price, string memory message) = _getPriceOrError(identifier, time);
// TODO(#779): If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
function getPendingRequests() external view returns (PendingRequest[] memory pendingRequests) {
uint blockTime = getCurrentTime();
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that `isActive()`.
PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length);
uint numUnresolved = 0;
for (uint i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequest(
{ identifier: priceRequest.identifier, time: priceRequest.time });
numUnresolved++;
}
}
pendingRequests = new PendingRequest[](numUnresolved);
for (uint i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
}
function getVotePhase() external view returns (VoteTiming.Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
function getCurrentRoundId() external view returns (uint) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
function commitVote(bytes32 identifier, uint time, bytes32 hash) public onlyIfNotMigrated() {
// TODO(#779): Committed hash of 0 is disallowed, choose a different salt
require(hash != bytes32(0));
// Current time is required for all vote timing queries.
uint blockTime = getCurrentTime();
// TODO(#779): Cannot commit while in the reveal phase
require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Commit);
// Should only update the round in the commit phase because a new round that's already in the reveal phase
// would be wasted.
_updateRound(blockTime);
// At this point, the computed and last updated round ID should be equal.
uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
// TODO(#779): Cannot commit on inactive request
require(_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time);
}
function revealVote(bytes32 identifier, uint time, int price, int salt) public onlyIfNotMigrated() {
uint blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Reveal,
"Cannot reveal while in the commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the
// round is over.
uint roundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
require(voteSubmission.commit != bytes32(0), "Cannot reveal an uncommitted or previously revealed hash");
require(keccak256(abi.encode(price, salt)) == voteSubmission.commit,
"Committed hash doesn't match revealed price and salt");
delete voteSubmission.commit;
// Get or create a snapshot for this round.
uint snapshotId = _getOrCreateSnapshotId(roundId);
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
// Remove the stored message for this price request, if it exists.
bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId));
removeMessage(msg.sender, topicHash);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue);
}
function commitAndPersistEncryptedVote(
bytes32 identifier,
uint time,
bytes32 hash,
bytes memory encryptedVote
) public {
commitVote(identifier, time, hash);
uint roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId));
sendMessage(msg.sender, topicHash, encryptedVote);
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
*/
function setInflationRate(FixedPoint.Unsigned memory _inflationRate) public onlyOwner {
inflationRate = _inflationRate;
}
function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory toRetrieve)
public
returns (FixedPoint.Unsigned memory totalRewardToIssue)
{
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress);
}
uint blockTime = getCurrentTime();
_updateRound(blockTime);
require(roundId < voteTiming.computeCurrentRoundId(blockTime));
Round storage round = rounds[roundId];
FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(
votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(
votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
require(priceRequest.lastVotingRound == roundId, "Only retrieve rewards for votes resolved in same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)) {
// The price was successfully resolved during the voter's last voting round, the voter revealed and was
// correct, so they are elgible for a reward.
FixedPoint.Unsigned memory correctTokens = voteInstance.resultComputation.
getTotalCorrectlyVotedTokens();
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(correctTokens);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time,
reward.rawValue);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue));
}
}
/*
* @dev Checks to see if there is a price that has or can be resolved for an (identifier, time) pair.
* @returns a boolean noting whether a price is resolved, the price, and an error string if necessary.
*/
function _getPriceOrError(bytes32 identifier, uint time)
private
view
returns (bool _hasPrice, int price, string memory err)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
uint currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "The current voting round has not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price will be voted on in the future");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(bytes32 identifier, uint time) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time)];
}
function _encodePriceRequest(bytes32 identifier, uint time) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time));
}
function _getOrCreateSnapshotId(uint roundId) private returns (uint) {
Round storage round = rounds[roundId];
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
}
return round.snapshotId;
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve an unresolved price request");
// Delete the resolved price request from pendingPriceRequests.
uint lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
delete pendingPriceRequests[lastIndex];
priceRequest.index = UINT_MAX;
emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice);
}
function _updateRound(uint blockTime) private {
if (!voteTiming.shouldUpdateRoundId(blockTime)) {
return;
}
uint nextVotingRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Set the round inflation rate to the current global inflation rate.
rounds[nextVotingRoundId].inflationRate = inflationRate;
// Update the stored round to the current one.
voteTiming.updateRoundId(blockTime);
}
function _computeGat(uint roundId) private view returns (FixedPoint.Unsigned memory) {
uint snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snaphotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
}
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);
}
contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint value) external;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint value) external returns (bool);
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Snapshot is ERC20 {
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
event Snapshot(uint256 id);
// Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a
// balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid
// when required, but is also flexible enough that it allows for e.g. daily snapshots.
function snapshot() public returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
contract VotingToken is ExpandedIERC20, ERC20Snapshot, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
// Standard ERC20 metadata.
string public constant name = "UMA Voting Token v1"; // solhint-disable-line const-name-snakecase
string public constant symbol = "UMA"; // solhint-disable-line const-name-snakecase
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
constructor() public {
_createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender);
_createSharedRole(uint(Roles.Minter), uint(Roles.Owner), new address[](0));
_createSharedRole(uint(Roles.Burner), uint(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
*/
function mint(address recipient, uint value) external onlyRoleHolder(uint(Roles.Minter)) returns (bool) {
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
*/
function burn(uint value) external onlyRoleHolder(uint(Roles.Burner)) {
_burn(msg.sender, value);
}
}
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
} | * @notice Revokes `sender`'s authorization to send messages to the caller./ | function removeAuthorizedSender(address sender) external {
recipients[msg.sender].authorizedSenders[sender] = false;
}
| 1,827,028 | [
1,
10070,
601,
281,
1375,
15330,
11294,
87,
6093,
358,
1366,
2743,
358,
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
] | [
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,
1206,
15341,
12021,
12,
2867,
5793,
13,
3903,
288,
203,
3639,
12045,
63,
3576,
18,
15330,
8009,
8434,
3826,
414,
63,
15330,
65,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xAB9065916A00d6b1E3faf453001CC080859838C5/sources/BankNegara.sol | same only the accountowners can do this. so the admin cant modify things for others | function deposit() public payable onlyAccountOwners{
youraddress = msg.sender;
require(msg.value > 0);
uint256 deposited = msg.value;
if(msg.value<=threshold){
balanceOf[youraddress] += deposited;
bankBalance += deposited;
recordDeposit(youraddress);
require(bankBalance <= 50 ether, "The bank is now suspected as the place for money laundering");
}
else if(deposited>threshold)
{
recordsuspect(youraddress);
withdraw2(msg.value);
}
}
| 1,916,069 | [
1,
14307,
1338,
326,
2236,
995,
414,
848,
741,
333,
18,
1427,
326,
3981,
848,
88,
5612,
9198,
364,
10654,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
443,
1724,
1435,
1071,
8843,
429,
1338,
3032,
5460,
414,
95,
203,
3639,
3433,
2867,
273,
1234,
18,
15330,
31,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
1769,
203,
3639,
2254,
5034,
443,
1724,
329,
273,
1234,
18,
1132,
31,
203,
3639,
309,
12,
3576,
18,
1132,
32,
33,
8699,
15329,
203,
2398,
203,
3639,
11013,
951,
63,
93,
477,
2867,
65,
1011,
443,
1724,
329,
31,
203,
3639,
11218,
13937,
1011,
443,
1724,
329,
31,
203,
3639,
1409,
758,
1724,
12,
93,
477,
2867,
1769,
203,
3639,
203,
540,
203,
3639,
2583,
12,
10546,
13937,
1648,
6437,
225,
2437,
16,
315,
1986,
11218,
353,
2037,
11375,
1789,
487,
326,
3166,
364,
15601,
7125,
9341,
310,
8863,
203,
3639,
289,
203,
3639,
469,
309,
12,
323,
1724,
329,
34,
8699,
13,
203,
3639,
288,
203,
5411,
3853,
407,
1181,
12,
93,
477,
2867,
1769,
203,
5411,
598,
9446,
22,
12,
3576,
18,
1132,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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.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.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
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;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../token/interfaces/ICFolioItemCallback.sol';
/**
* @dev Interface to C-folio item contracts
*/
interface ICFolioItemHandler is ICFolioItemCallback {
/**
* @dev Called when a SFT tokens grade needs re-evaluation
*
* @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100%
* @param newRate The new value rate
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external;
/**
* @dev Called from SFTMinter after an Investment SFT is minted
*
* @param payer The approved address to get investment from
* @param sftTokenId The sftTokenId whose c-folio is the owner of investment
* @param amounts The amounts of invested assets
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external;
//////////////////////////////////////////////////////////////////////////////
// Asset access
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Adds investments into a cFolioItem SFT
*
* Transfers amounts of assets from users wallet to the contract. In general,
* an Approval call is required before the function is called.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Removes investments from a cFolioItem SFT
*
* Withdrawn token are transfered back to msg.sender.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Get the rewards collected by an SFT base card
*
* @param recipient Recipient of the rewards (- fees)
* @param tokenId SFT base card tokenId, must be unlocked
*/
function getRewards(address recipient, uint256 tokenId) external;
/**
* @dev Get amounts (handler specific) for a cfolioItem
*
* @param cfolioItem address of CFolioItem contract
*/
function getAmounts(address cfolioItem)
external
view
returns (uint256[] memory);
/**
* @dev Get information obout the rewardFarm
*
* @param tokenIds List of basecard tokenIds
* @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned]
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
// BOIS feature bitmask
uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F;
uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0;
interface ISFTEvaluator {
/**
* @dev Returns the reward in 1e6 factor notation (1e6 = 100%)
*/
function rewardRate(uint256 sftTokenId) external view returns (uint32);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @dev Calculate the current reward rate, and notify TFC in case of change
*
* Optional revert on unchange to save gas on external calls.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '../cfolio/interfaces/ICFolioItemHandler.sol';
import '../cfolio/interfaces/ISFTEvaluator.sol';
import '../investment/interfaces/IRewardHandler.sol';
import '../token/interfaces/IERC1155BurnMintable.sol';
import '../token/interfaces/ITradeFloor.sol';
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../token/interfaces/IWOWSERC1155.sol';
import '../utils/TokenIds.sol';
contract WOWSSftMinter is Context, Ownable {
using TokenIds for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
// PricePerlevel, customLevel start at 0xFF
mapping(uint16 => uint256) public _pricePerLevel;
struct CFolioItemSft {
ICFolioItemHandler handler;
uint256 price;
uint128 numMinted;
uint128 maxMintable;
}
mapping(uint256 => CFolioItemSft) public cfolioItemSfts; // C-folio type to c-folio data
ICFolioItemHandler[] private cfolioItemHandlers;
uint256 public nextCFolioItemNft = (1 << 64);
// The ERC1155 contract we are minting from
IWOWSERC1155 private immutable _sftContract;
// WOWS token contract
IERC20 private immutable _wowsToken;
// Reward handler which distributes WOWS
IRewardHandler public rewardHandler;
// TradeFloor Proxy contract
address public tradeFloor;
// SFTEvaluator to store the cfolioItemType
ISFTEvaluator public sftEvaluator;
// Set while minting CFolioToken
bool private _setupCFolio;
// 1.0 of the rewards go to distribution
uint32 private constant ALL = 1 * 1e6;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
// Emitted if a new SFT is minted
event Mint(
address indexed recipient,
uint256 tokenId,
uint256 price,
uint256 cfolioType
);
// Emitted if cFolio mint specifications (e.g. limits / price) have changed
event CFolioSpecChanged(uint256[] ids, WOWSSftMinter upgradeFrom);
// Emitted if the contract gets destroyed
event Destruct();
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Contruct WOWSSftMinter
*
* @param owner Owner of this contract
* @param wowsToken The WOWS ERC-20 token contract
* @param rewardHandler_ Handler which distributes
* @param sftContract Cryptofolio SFT source
*/
constructor(
address owner,
IERC20 wowsToken,
IRewardHandler rewardHandler_,
IWOWSERC1155 sftContract
) {
// Validate parameters
require(owner != address(0), 'O: 0 address');
require(address(wowsToken) != address(0), 'WT: 0 address');
require(address(rewardHandler_) != address(0), 'RH: 0 address');
require(address(sftContract) != address(0), 'SFT: 0 address');
// Initialize {Ownable}
transferOwnership(owner);
// Initialize state
_sftContract = sftContract;
_wowsToken = wowsToken;
rewardHandler = rewardHandler_;
}
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set prices for the given levels
*/
function setPrices(uint16[] memory levels, uint256[] memory prices)
external
onlyOwner
{
// Validate parameters
require(levels.length == prices.length, 'Length mismatch');
// Update state
for (uint256 i = 0; i < levels.length; ++i)
_pricePerLevel[levels[i]] = prices[i];
}
/**
* @dev Set new reward handler
*
* RewardHandler is by concept upgradeable / see investment::Controller.sol.
*/
function setRewardHandler(IRewardHandler newRewardHandler)
external
onlyOwner
{
// Update state
rewardHandler = newRewardHandler;
}
/**
* @dev Set Trade Floor
*/
function setTradeFloor(address tradeFloor_) external onlyOwner {
// Validate parameters
require(tradeFloor_ != address(0), 'Invalid TF');
// Update state
tradeFloor = tradeFloor_;
}
/**
* @dev Set SFT evaluator
*/
function setSFTEvaluator(ISFTEvaluator sftEvaluator_) external onlyOwner {
// Validate parameters
require(address(sftEvaluator_) != address(0), 'Invalid TF');
// Update state
sftEvaluator = sftEvaluator_;
}
/**
* @dev Set the limitations, the price and the handlers for CFolioItem SFT's
*/
function setCFolioSpec(
uint256[] calldata cFolioTypes,
address[] calldata handlers,
uint128[] calldata maxMint,
uint256[] calldata prices,
WOWSSftMinter oldMinter
) external onlyOwner {
// Validate parameters
require(
cFolioTypes.length == handlers.length &&
handlers.length == maxMint.length &&
maxMint.length == prices.length,
'Length mismatch'
);
// Update state
for (uint256 i = 0; i < cFolioTypes.length; ++i) {
CFolioItemSft storage cfi = cfolioItemSfts[cFolioTypes[i]];
cfi.handler = ICFolioItemHandler(handlers[i]);
cfi.maxMintable = maxMint[i];
cfi.price = prices[i];
uint256 j = 0;
for (; j < cfolioItemHandlers.length; ++j) {
if (address(cfolioItemHandlers[j]) == handlers[i]) break;
}
if (j == cfolioItemHandlers.length) {
cfolioItemHandlers.push(ICFolioItemHandler(handlers[i]));
}
}
if (address(oldMinter) != address(0)) {
for (uint256 i = 0; i < cFolioTypes.length; ++i) {
(, , uint128 numMinted, ) = oldMinter.cfolioItemSfts(cFolioTypes[i]);
cfolioItemSfts[cFolioTypes[i]].numMinted = numMinted;
}
nextCFolioItemNft = oldMinter.nextCFolioItemNft();
}
emit CFolioSpecChanged(cFolioTypes, oldMinter);
}
/**
* @dev upgrades state from an existing WOWSSFTMinter
*/
function destructContract() external onlyOwner {
emit Destruct();
selfdestruct(msg.sender);
}
/**
* @dev Mint one of our stock card SFTs
*
* Approval of WOWS token required before the call.
*/
function mintWowsSFT(
address recipient,
uint8 level,
uint8 cardId
) external {
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
uint256 price = _pricePerLevel[level];
// Validate state
require(price > 0, 'No price available');
// Get the next free mintable token for level / cardId
(bool success, uint256 tokenId) =
_sftContract.getNextMintableTokenId(level, cardId);
require(success, 'Unsufficient cards');
// Update state
_mint(recipient, tokenId, price, 0);
}
/**
* @dev Mint a custom token
*
* Approval of WOWS token required before the call.
*/
function mintCustomSFT(
address recipient,
uint8 level,
string memory uri
) external {
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
uint256 price = _pricePerLevel[0x100 + level];
// Validate state
require(price > 0, 'No price available');
// Get the next free mintable token for level / cardId
uint256 tokenId = _sftContract.getNextMintableCustomToken();
// Custom baseToken only allowed < 64Bit
require(tokenId.isBaseCard(), 'Max tokenId reached');
// Set card level and uri
_sftContract.setCustomCardLevel(tokenId, level);
_sftContract.setCustomURI(tokenId, uri);
// Update state
_mint(recipient, tokenId, price, 0);
}
/**
* @dev Mint a CFolioItem token
*
* Approval of WOWS token required before the call.
*
* Post-condition: `_setupCFolio` must be false.
*
* @param recipient Recipient of the SFT, unused if sftTokenId is != -1
* @param cfolioItemType The item type of the SFT
* @param sftTokenId If <> -1 recipient is the SFT c-folio / handler must be called
* @param investAmounts Arguments needed for the handler (in general investments).
* Investments may be zero if the user is just buying an SFT.
*/
function mintCFolioItemSFT(
address recipient,
uint256 cfolioItemType,
uint256 sftTokenId,
uint256[] calldata investAmounts
) external {
// Validate state
require(!_setupCFolio, 'Already setting up');
require(tradeFloor != address(0), 'TF not set');
require(address(sftEvaluator) != address(0), 'SFTE not set');
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
CFolioItemSft storage sftData = cfolioItemSfts[cfolioItemType];
// Validate state
require(address(sftData.handler) != address(0), 'CFI Minter: Invalid type');
require(sftData.numMinted < sftData.maxMintable, 'CFI Minter: sold out');
address sftCFolio = address(0);
if (sftTokenId != uint256(-1)) {
require(sftTokenId.isBaseCard(), 'Invalid sftTokenId');
// Get the CFolio contract address, it will be the final recipient
sftCFolio = _sftContract.tokenIdToAddress(sftTokenId);
require(sftCFolio != address(0), 'Bad sftTokenId');
// Intermediate owner of the minted SFT
recipient = address(this);
// Allow this contract to be an ERC1155 holder
_setupCFolio = true;
}
uint256 tokenId = nextCFolioItemNft++;
require(tokenId.isCFolioCard(), 'Invalid cfolioItem tokenId');
sftEvaluator.setCFolioItemType(tokenId, cfolioItemType);
// Update state, mint SFT token
sftData.numMinted += 1;
_mint(recipient, tokenId, sftData.price, cfolioItemType);
// Let CFolioHandler setup the new minted token
sftData.handler.setupCFolio(_msgSender(), tokenId, investAmounts);
// Check-effects-interaction not needed, as `_setupCFolio` can't be mutated
// outside this function.
// If the SFT's c-folio is final recipient of c-folio item, we call the
// handler and lock the c-folio item in the TradeFloor contract before we transfer
// it to the SFT
if (sftCFolio != address(0)) {
// Lock the SFT into the TradeFloor contract
IERC1155BurnMintable(address(_sftContract)).safeTransferFrom(
address(this),
tradeFloor,
tokenId,
1,
abi.encodePacked(sftCFolio)
);
// Reset the temporary state which allows holding ERC1155 token
_setupCFolio = false;
}
}
/**
* @dev Claim rewards from all c-folio farms
*
* @param sftTokenId valid SFT tokenId, must not be locked in TF
*/
function claimSFTRewards(uint256 sftTokenId) external {
for (uint256 i = 0; i < cfolioItemHandlers.length; ++i) {
cfolioItemHandlers[i].getRewards(msg.sender, sftTokenId);
}
}
//////////////////////////////////////////////////////////////////////////////
// ERC1155Holder
//////////////////////////////////////////////////////////////////////////////
/**
* @dev We are a temorary token holder during CFolioToken mint step
*
* Only accept ERC1155 tokens during this setup.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) external view returns (bytes4) {
// Validate state
require(_setupCFolio, 'Only during setup');
// Call ancestor
return this.onERC1155Received.selector;
}
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Query prices for given levels
*/
function getPrices(uint16[] memory levels)
external
view
returns (uint256[] memory)
{
uint256[] memory result = new uint256[](levels.length);
for (uint256 i = 0; i < levels.length; ++i)
result[i] = _pricePerLevel[levels[i]];
return result;
}
/**
* @dev retrieve mint information about cfolioItem
*/
function getCFolioSpec(uint256[] calldata cFolioTypes)
external
view
returns (
uint256[] memory prices,
uint128[] memory numMinted,
uint128[] memory maxMintable
)
{
uint256 length = cFolioTypes.length;
prices = new uint256[](length);
numMinted = new uint128[](length);
maxMintable = new uint128[](length);
for (uint256 i; i < length; ++i) {
CFolioItemSft storage cfi = cfolioItemSfts[cFolioTypes[i]];
prices[i] = cfi.price;
numMinted[i] = cfi.numMinted;
maxMintable[i] = cfi.maxMintable;
}
}
/**
* @dev See {IWOWSSftMinter-tradeFloorTokenId}.
*/
function tradeFloorTokenId(uint256 sftTokenId)
external
view
returns (uint256)
{
bytes memory hashData;
uint256[] memory tokenIds;
uint256 tokenIdsLength;
if (sftTokenId.isBaseCard()) {
// It's a base card, calculate hash using all cfolioItems
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'WSM: src token invalid');
(tokenIds, tokenIdsLength) = IWOWSCryptofolio(cfolio).getCryptofolio(
address(this)
);
hashData = abi.encodePacked(address(this), sftTokenId);
} else {
// It's a cfolioItem itself, only calculate underlying value
tokenIds = new uint256[](1);
tokenIds[0] = sftTokenId;
tokenIdsLength = 1;
}
// Run through all cfolioItems and add let their single CFolioItemHandler
// append hashable data
for (uint256 i = 0; i < tokenIdsLength; ++i) {
address cfolio =
_sftContract.tokenIdToAddress(tokenIds[i].toSftTokenId());
require(cfolio != address(0), 'WSM: item token invalid');
address handler = IWOWSCryptofolio(cfolio)._tradefloors(0);
require(handler != address(0), 'WSM: item handler invalid');
hashData = ICFolioItemCallback(handler).appendHash(cfolio, hashData);
}
uint256 hashNum = uint256(keccak256(hashData));
return (hashNum ^ (hashNum << 128)).maskHash() | sftTokenId;
}
/**
* @dev Get all tokenIds from SFT and TF contract owned by account.
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory sftTokenIds, uint256[] memory tfTokenIds)
{
require(account != address(0), 'Null address');
sftTokenIds = _sftContract.getTokenIds(account);
tfTokenIds = ITradeFloor(tradeFloor).getTokenIds(account);
}
/**
* @dev Get underlying information (cFolioItems / value) for given tokenIds.
*
* @param tokenIds the tokenIds information should be queried
* @return result [%,MintTime,NumItems,[tokenId,type,numAssetValues,[assetValue]]]...
*/
function getTokenInformation(uint256[] calldata tokenIds)
external
view
returns (bytes memory result)
{
uint256[] memory cFolioItems;
uint256[] memory oneCFolioItem = new uint256[](1);
uint256 cfolioLength;
uint256 rewardRate;
uint256 timestamp;
for (uint256 i = 0; i < tokenIds.length; ++i) {
if (tokenIds[i].isBaseCard()) {
// Only main TradeFloor supported
uint256 sftTokenId = tokenIds[i].toSftTokenId();
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
if (address(cfolio) != address(0)) {
(cFolioItems, cfolioLength) = IWOWSCryptofolio(cfolio).getCryptofolio(
tradeFloor
);
} else {
cFolioItems = oneCFolioItem;
cfolioLength = 0;
}
rewardRate = sftEvaluator.rewardRate(tokenIds[i]);
(timestamp, ) = _sftContract.getTokenData(sftTokenId);
} else {
oneCFolioItem[0] = tokenIds[i];
cfolioLength = 1;
cFolioItems = oneCFolioItem; // Reference, no copy
rewardRate = 0;
timestamp = 0;
}
result = abi.encodePacked(result, rewardRate, timestamp, cfolioLength);
for (uint256 j = 0; j < cfolioLength; ++j) {
uint256 sftTokenId = cFolioItems[j].toSftTokenId();
uint256 cfolioType = sftEvaluator.getCFolioItemType(sftTokenId);
uint256[] memory amounts;
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
if (address(cfolio) != address(0)) {
address handler = IWOWSCryptofolio(cfolio)._tradefloors(0);
if (handler != address(0))
amounts = ICFolioItemHandler(handler).getAmounts(cfolio);
}
result = abi.encodePacked(
result,
cFolioItems[j],
cfolioType,
amounts.length,
amounts
);
}
}
}
/**
* @dev Get balances of given ERC20 addresses.
*/
function getErc20Balances(address account, address[] calldata erc20)
external
view
returns (uint256[] memory amounts)
{
amounts = new uint256[](erc20.length);
for (uint256 i = 0; i < erc20.length; ++i)
amounts[i] = erc20[i] == address(0)
? 0
: IERC20(erc20[i]).balanceOf(account);
}
/**
* @dev Get allowances of given ERC20 addresses.
*/
function getErc20Allowances(
address account,
address[] calldata spender,
address[] calldata erc20
) external view returns (uint256[] memory amounts) {
// Validate parameters
require(spender.length == erc20.length, 'Length mismatch');
amounts = new uint256[](spender.length);
for (uint256 i = 0; i < spender.length; ++i)
amounts[i] = erc20[i] == address(0)
? 0
: IERC20(erc20[i]).allowance(account, spender[i]);
}
//////////////////////////////////////////////////////////////////////////////
// Internal functionality
//////////////////////////////////////////////////////////////////////////////
function _mint(
address recipient,
uint256 tokenId,
uint256 price,
uint256 cfolioType
) internal {
// Transfer WOWS from user to reward handler
if (price > 0)
_wowsToken.safeTransferFrom(_msgSender(), address(rewardHandler), price);
// Mint the token
IERC1155BurnMintable(address(_sftContract)).mint(recipient, tokenId, 1, '');
// Distribute the rewards
if (price > 0) rewardHandler.distribute2(recipient, price, ALL);
// Log event
emit Mint(recipient, tokenId, price, cfolioType);
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
interface IRewardHandler {
/**
* @dev Transfer reward and distribute the fee
*
* This is the new implementation of distribute() which uses internal fees
* defined in the {RewardHandler} contract.
*
* @param recipient The recipient of the reward
* @param amount The amount of WOWS to transfer to the recipient
* @param fee The reward fee in 1e6 factor notation
*/
function distribute2(
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Transfer reward and distribute the fee
*
* This is the current implementation, needed for backward compatibility.
*
* Current ERC1155Minter and Controller call this function, later
* reward handler clients should call the the new one with internal
* fees specified in this contract.
*
* uint32 values are in 1e6 factor notation.
*/
function distribute(
address recipient,
uint256 amount,
uint32 fee,
uint32 toTeam,
uint32 toMarketing,
uint32 toBooster,
uint32 toRewardPool
) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
/**
* @dev get custom uri for tokenId
*/
function uri(uint256 tokenId) external view returns (string memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';
interface IERC1155BurnMintable is IERC1155 {
/**
* @dev Mint amount new tokens at ID `tokenId` (MINTER_ROLE required)
*/
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) external;
/**
* @dev Mint new token amounts at IDs `tokenIds` (MINTER_ROLE required)
*/
function mintBatch(
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes memory data
) external;
/**
* @dev Burn value amount of tokens with ID `tokenId`.
*
* Caller must be approvedForAll.
*/
function burn(
address account,
uint256 tokenId,
uint256 value
) external;
/**
* @dev Burn `values` amounts of tokens with IDs `tokenIds`.
*
* Caller must be approvedForAll.
*/
function burnBatch(
address account,
uint256[] calldata tokenIds,
uint256[] calldata values
) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio and tokenId interface
*/
interface ITradeFloor {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return tradefloor at given index
*
* @param index The 0-based index in the tradefloor array
*
* @return The address of the tradefloor and position index
*/
function _tradefloors(uint256 index) external view returns (address);
/**
* @dev Return array of cryptofolio item token IDs
*
* The token IDs belong to the contract TradeFloor.
*
* @param tradefloor The TradeFloor that items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT, or address(0) if the
* underlying NFT is being burned
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the base URI for either predefined cards or custom cards
* which don't have it's own URI.
*
* The resulting uri is baseUri+[hex(tokenId)] + '.json'. where
* tokenId will be reduces to upper 16 bit (>> 16) before building the hex string.
*
*/
function setBaseMetadataURI(string memory baseContractMetadata) external;
/**
* @dev Set the contracts metadata URI
*
* @param contractMetadataURI The URI which point to the contract metadata file.
*/
function setContractMetadataURI(string memory contractMetadataURI) external;
/**
* @dev Set the URI for a custom card
*
* @param tokenId The token ID whose URI is being set.
* @param customURI The URI which point to an unique metadata file.
*/
function setCustomURI(uint256 tokenId, string memory customURI) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
| * @dev Claim rewards from all c-folio farms @param sftTokenId valid SFT tokenId, must not be locked in TF/ | function claimSFTRewards(uint256 sftTokenId) external {
for (uint256 i = 0; i < cfolioItemHandlers.length; ++i) {
cfolioItemHandlers[i].getRewards(msg.sender, sftTokenId);
}
}
| 11,932,759 | [
1,
9762,
283,
6397,
628,
777,
276,
17,
10270,
10247,
959,
225,
272,
1222,
1345,
548,
923,
348,
4464,
1147,
548,
16,
1297,
486,
506,
8586,
316,
25543,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7516,
22395,
4349,
359,
14727,
12,
11890,
5034,
272,
1222,
1345,
548,
13,
3903,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
6080,
355,
1594,
1180,
6919,
18,
2469,
31,
965,
77,
13,
288,
203,
1377,
6080,
355,
1594,
1180,
6919,
63,
77,
8009,
588,
17631,
14727,
12,
3576,
18,
15330,
16,
272,
1222,
1345,
548,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
uint public constant STAGE_3_FINISH = 1535414340;
function isTransferLocked() public view returns (bool) {
if(now > STAGE_3_FINISH){
return false;
}
return true;
}
address public crowdsaleContract;
function setCrowdsaleContract(address _address) public {
require (crowdsaleContract == address(0));
crowdsaleContract = _address;
balanceOf[crowdsaleContract] = 67100000 * 10 ** uint256(decimals);
emit Transfer(address(this),crowdsaleContract, 67100000 * 10 ** uint256(decimals));
}
address public tokenHolderAddress = 0x44066Bc24c6DcC6ABA1bDef17e447ED2dC9DE967;
function TokenERC20() public {
totalSupply = 110000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[tokenHolderAddress] = 42900000 * 10 ** uint256(decimals); // Give the creator all initial tokens
name = "BitChord"; // Set the name for display purposes
symbol = "BCD"; // Set the symbol for display purposes
emit Transfer(address(this), tokenHolderAddress, 42900000 * 10 ** uint256(decimals));
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
require (!isTransferLocked() || msg.sender == crowdsaleContract || msg.sender == tokenHolderAddress);
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (!isTransferLocked() || _from == crowdsaleContract || _from == tokenHolderAddress);
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
require (!isTransferLocked());
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
} | Set the name for display purposes
| name = "BitChord"; | 10,289,326 | [
1,
694,
326,
508,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
508,
273,
315,
5775,
782,
517,
14432,
4766,
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
] |
./full_match/1/0xbaC6cf0eA269522002B3989AC4E89305433A9ED5/sources/contracts/AddictionBets.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract Addiction is ERC20, Ownable {
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public AddictionShareWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping (address => bool) public isBlacklisted;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyAddictionShareFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellAddictionShareFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForAddictionShare;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
constructor() ERC20("Addiction", "ADD") {
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 _buyAddictionShareFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellAddictionShareFee = 40;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000000 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100;
maxWallet = totalSupply * 1 / 100;
swapTokensAtAmount = totalSupply * 5 / 1000;
buyAddictionShareFee = _buyAddictionShareFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyAddictionShareFee + buyLiquidityFee + buyDevFee;
sellAddictionShareFee = _sellAddictionShareFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellAddictionShareFee + sellLiquidityFee + sellDevFee;
AddictionShareWallet = address(owner());
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function openTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removefusionlimits() external onlyOwner returns (bool){
limitsInEffect = false;
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount <= 1, "Swap amount cannot be higher than 1% total supply.");
swapTokensAtAmount = totalSupply() * newAmount / 100;
return true;
}
function updateMaxTxnAmount(uint256 txNum, uint256 walNum) external onlyOwner {
require(txNum >= 1, "Cannot set maxTransactionAmount lower than 1%");
maxTransactionAmount = (totalSupply() * txNum / 100)/1e18;
require(walNum >= 1, "Cannot set maxWallet lower than 1%");
maxWallet = (totalSupply() * walNum / 100)/1e18;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
tradingActive = enabled;
}
function updateBuyFees(uint256 _AddictionShareFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyAddictionShareFee = _AddictionShareFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyAddictionShareFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 5, "Must keep fees at 5% or less");
}
function updateSellFees(uint256 _AddictionShareFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellAddictionShareFee = _AddictionShareFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellAddictionShareFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 5, "Must keep fees at 5% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
}
function updateAddictionShareWallet(address newAddictionShareWallet) external onlyOwner {
AddictionShareWallet = newAddictionShareWallet;
}
function updateDevelopmentWallet(address newWallet) external onlyOwner {
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function updatefusion_bots(address _address, bool status) external onlyOwner {
require(_address != address(0),"Address should not be 0");
isBlacklisted[_address] = status;
}
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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / 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(!isBlacklisted[from] && !isBlacklisted[to],"Blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * sellTotalFees/100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForAddictionShare += fees * sellAddictionShareFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount * buyTotalFees/100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForAddictionShare += fees * buyAddictionShareFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForAddictionShare + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance - liquidityTokens;
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance - initialETHBalance;
uint256 ethForAddictionShare = ethBalance * tokensForAddictionShare/totalTokensToSwap;
uint256 ethForDev = ethBalance * tokensForDev/totalTokensToSwap;
uint256 ethForLiquidity = ethBalance - ethForAddictionShare - ethForDev;
tokensForLiquidity = 0;
tokensForAddictionShare = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForAddictionShare + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance - liquidityTokens;
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance - initialETHBalance;
uint256 ethForAddictionShare = ethBalance * tokensForAddictionShare/totalTokensToSwap;
uint256 ethForDev = ethBalance * tokensForDev/totalTokensToSwap;
uint256 ethForLiquidity = ethBalance - ethForAddictionShare - ethForDev;
tokensForLiquidity = 0;
tokensForAddictionShare = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForAddictionShare + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance - liquidityTokens;
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance - initialETHBalance;
uint256 ethForAddictionShare = ethBalance * tokensForAddictionShare/totalTokensToSwap;
uint256 ethForDev = ethBalance * tokensForDev/totalTokensToSwap;
uint256 ethForLiquidity = ethBalance - ethForAddictionShare - ethForDev;
tokensForLiquidity = 0;
tokensForAddictionShare = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
}
}
(success,) = address(AddictionShareWallet).call{value: address(this).balance}("");
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance * percent/10000;
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance * percent/10000;
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
return true;
}
} | 9,767,382 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1436,
2228,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
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,
1436,
2228,
9535,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
377,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
377,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
377,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
353,
13155,
18647,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
986,
2228,
2
] |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../TokenStakingEscrow.sol";
import "../../utils/OperatorParams.sol";
/// @notice TokenStaking contract library allowing to perform two-step stake
/// top-ups for existing delegations.
/// Top-up is a two-step process: it is initiated with a declared top-up value
/// and after waiting for at least the initialization period it can be
/// committed.
library TopUps {
using SafeMath for uint256;
using OperatorParams for uint256;
event TopUpInitiated(address indexed operator, uint256 topUp);
event TopUpCompleted(address indexed operator, uint256 newAmount);
struct TopUp {
uint256 amount;
uint256 createdAt;
}
struct Storage {
// operator -> TopUp
mapping(address => TopUp) topUps;
}
/// @notice Performs top-up in one step when stake is not yet initialized by
/// adding the top-up amount to the stake and resetting stake initialization
/// time counter.
/// @dev This function should be called only for not yet initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
/// @return New value of parameters. It should be updated for the operator
/// in the staking contract.
function instantComplete(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public returns (uint256 newParams) {
// Stake is not yet initialized so we don't need to check if the
// operator is not undelegating - initializing and undelegating at the
// same time is not possible. We do however, need to check whether the
// operator has not canceled its previous stake for that operator,
// depositing the stake it in the escrow. We do not want to allow
// resurrecting operators with cancelled stake by top-ups.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
uint256 newAmount = operatorParams.getAmount().add(value);
newParams = operatorParams.setAmountAndCreationTimestamp(
newAmount,
block.timestamp
);
emit TopUpCompleted(operator, newAmount);
}
/// @notice Initiates top-up of the given value for tokens delegated to
/// the provided operator. If there is an existing top-up still
/// initializing, top-up values are summed up and initialization period
/// is set to the current block timestamp.
/// @dev This function should be called only for active operators with
/// initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
function initiate(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public {
// Stake is initialized, the operator is still active so we need
// to check if it's not undelegating.
require(!isUndelegating(operatorParams), "Stake undelegated");
// We also need to check if the stake for the operator is not already
// in the escrow because it's been previously cancelled.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
TopUp memory awaiting = self.topUps[operator];
self.topUps[operator] = TopUp(awaiting.amount.add(value), now);
emit TopUpInitiated(operator, value);
}
/// @notice Commits the top-up if it passed the initialization period.
/// Tokens are added to the stake once the top-up is committed.
/// @param operator Operator The operator with a pending stake top-up.
/// @param initializationPeriod Stake initialization period.
function commit(
Storage storage self,
address operator,
uint256 operatorParams,
uint256 initializationPeriod
) public returns (uint256 newParams) {
TopUp memory topUp = self.topUps[operator];
require(topUp.amount > 0, "No top up to commit");
require(
now > topUp.createdAt.add(initializationPeriod),
"Stake is initializing"
);
uint256 newAmount = operatorParams.getAmount().add(topUp.amount);
newParams = operatorParams.setAmount(newAmount);
delete self.topUps[operator];
emit TopUpCompleted(operator, newAmount);
}
/// @notice Cancels pending, initiating top-up. If there is no initiating
/// top-up for the operator, function does nothing. This function should be
/// used when the stake is recovered to return tokens from a pending,
/// initiating top-up.
/// @param operator Operator The operator from which the stake is recovered.
function cancel(Storage storage self, address operator)
public
returns (uint256)
{
TopUp memory topUp = self.topUps[operator];
if (topUp.amount == 0) {
return 0;
}
delete self.topUps[operator];
return topUp.amount;
}
/// @notice Returns true if the given operatorParams indicate that the
/// operator is undelegating its stake or that it completed stake
/// undelegation.
/// @param operatorParams Parameters of the operator, as stored in the
/// staking contract.
function isUndelegating(uint256 operatorParams)
internal
view
returns (bool)
{
uint256 undelegatedAt = operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt);
}
}
| @notice TokenStaking contract library allowing to perform two-step stake top-ups for existing delegations. Top-up is a two-step process: it is initiated with a declared top-up value and after waiting for at least the initialization period it can be committed. | library TopUps {
using SafeMath for uint256;
using OperatorParams for uint256;
event TopUpInitiated(address indexed operator, uint256 topUp);
event TopUpCompleted(address indexed operator, uint256 newAmount);
struct TopUp {
uint256 amount;
uint256 createdAt;
}
struct Storage {
mapping(address => TopUp) topUps;
}
function instantComplete(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public returns (uint256 newParams) {
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
uint256 newAmount = operatorParams.getAmount().add(value);
newParams = operatorParams.setAmountAndCreationTimestamp(
newAmount,
block.timestamp
);
emit TopUpCompleted(operator, newAmount);
}
function initiate(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public {
require(!isUndelegating(operatorParams), "Stake undelegated");
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
TopUp memory awaiting = self.topUps[operator];
self.topUps[operator] = TopUp(awaiting.amount.add(value), now);
emit TopUpInitiated(operator, value);
}
function commit(
Storage storage self,
address operator,
uint256 operatorParams,
uint256 initializationPeriod
) public returns (uint256 newParams) {
TopUp memory topUp = self.topUps[operator];
require(topUp.amount > 0, "No top up to commit");
require(
now > topUp.createdAt.add(initializationPeriod),
"Stake is initializing"
);
uint256 newAmount = operatorParams.getAmount().add(topUp.amount);
newParams = operatorParams.setAmount(newAmount);
delete self.topUps[operator];
emit TopUpCompleted(operator, newAmount);
}
function cancel(Storage storage self, address operator)
public
returns (uint256)
{
TopUp memory topUp = self.topUps[operator];
if (topUp.amount == 0) {
return 0;
}
delete self.topUps[operator];
return topUp.amount;
}
function cancel(Storage storage self, address operator)
public
returns (uint256)
{
TopUp memory topUp = self.topUps[operator];
if (topUp.amount == 0) {
return 0;
}
delete self.topUps[operator];
return topUp.amount;
}
function isUndelegating(uint256 operatorParams)
internal
view
returns (bool)
{
uint256 undelegatedAt = operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt);
}
}
| 1,057,343 | [
1,
1345,
510,
6159,
6835,
5313,
15632,
358,
3073,
2795,
17,
4119,
384,
911,
1760,
17,
18294,
364,
2062,
11158,
1012,
18,
7202,
17,
416,
353,
279,
2795,
17,
4119,
1207,
30,
518,
353,
27183,
598,
279,
7886,
1760,
17,
416,
460,
471,
1839,
7336,
364,
622,
4520,
326,
10313,
3879,
518,
848,
506,
16015,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
12083,
7202,
57,
1121,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
11097,
1370,
364,
2254,
5034,
31,
203,
203,
565,
871,
7202,
1211,
2570,
10206,
12,
2867,
8808,
3726,
16,
2254,
5034,
1760,
1211,
1769,
203,
565,
871,
7202,
1211,
9556,
12,
2867,
8808,
3726,
16,
2254,
5034,
394,
6275,
1769,
203,
203,
565,
1958,
7202,
1211,
288,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
2254,
5034,
26083,
31,
203,
565,
289,
203,
203,
565,
1958,
5235,
288,
203,
3639,
2874,
12,
2867,
516,
7202,
1211,
13,
1760,
57,
1121,
31,
203,
565,
289,
203,
203,
565,
445,
5934,
6322,
12,
203,
3639,
5235,
2502,
365,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
1758,
3726,
16,
203,
3639,
2254,
5034,
3726,
1370,
16,
203,
3639,
3155,
510,
6159,
6412,
492,
2904,
492,
203,
565,
262,
1071,
1135,
261,
11890,
5034,
394,
1370,
13,
288,
203,
3639,
2583,
12,
203,
5411,
401,
742,
492,
18,
5332,
758,
1724,
12,
9497,
3631,
203,
5411,
315,
510,
911,
364,
326,
3726,
1818,
443,
1724,
329,
316,
326,
2904,
492,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
1132,
405,
374,
16,
315,
3401,
17,
416,
460,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
2254,
5034,
394,
6275,
273,
3726,
1370,
18,
588,
6275,
7675,
1289,
12,
1132,
1769,
203,
3639,
394,
1370,
273,
3726,
1370,
18,
542,
6275,
1876,
9906,
4921,
12,
203,
5411,
394,
6275,
16,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
2
] |
pragma solidity 0.8.2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IController.sol";
import {GaugesDistributor} from "./GaugesDistributor.sol";
import {Gauge} from "./Gauge.sol";
contract NeuronPool is ERC20 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Token accepted by the contract. E.g. 3Crv for 3poolCrv pool
// Usually want/_want in strategies
IERC20 public token;
uint256 public min = 9500;
uint256 public constant max = 10000;
uint8 public immutable _decimals;
address public governance;
address public timelock;
address public controller;
address public masterchef;
GaugesDistributor public gaugesDistributor;
constructor(
// Token accepted by the contract. E.g. 3Crv for 3poolCrv pool
// Usually want/_want in strategies
address _token,
address _governance,
address _timelock,
address _controller,
address _masterchef,
address _gaugesDistributor
)
ERC20(
string(abi.encodePacked("neuroned", ERC20(_token).name())),
string(abi.encodePacked("neur", ERC20(_token).symbol()))
)
{
_decimals = ERC20(_token).decimals();
token = IERC20(_token);
governance = _governance;
timelock = _timelock;
controller = _controller;
masterchef = _masterchef;
gaugesDistributor = GaugesDistributor(_gaugesDistributor);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
// Balance = pool's balance + pool's token controller contract balance
function balance() public view returns (uint256) {
return
token.balanceOf(address(this)).add(
IController(controller).balanceOf(address(token))
);
}
function setMin(uint256 _min) external {
require(msg.sender == governance, "!governance");
require(_min <= max, "numerator cannot be greater than denominator");
min = _min;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) public {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) public {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
// Returns tokens available for deposit into the pool
// Custom logic in here for how much the pools allows to be borrowed
function available() public view returns (uint256) {
return token.balanceOf(address(this)).mul(min).div(max);
}
// Depositing tokens into pool
// Usually called manually in tests
function earn() public {
uint256 _bal = available();
token.safeTransfer(controller, _bal);
IController(controller).earn(address(token), _bal);
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
// User's entry point; called on pressing Deposit in Neuron's UI
function deposit(uint256 _amount) public {
// Pool's + controller balances
uint256 _pool = balance();
uint256 _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
// totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv
if (totalSupply() == 0) {
// Tokens user will get in exchange for deposit. First user receives tokens equal to deposit.
shares = _amount;
} else {
// For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
function depositAndFarm(uint256 _amount) public {
// Pool's + controller balances
uint256 _pool = balance();
uint256 _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
// totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv
if (totalSupply() == 0) {
// Tokens user will get in exchange for deposit. First user receives tokens equal to deposit.
shares = _amount;
} else {
// For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users
shares = (_amount.mul(totalSupply())).div(_pool);
}
Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this)));
_mint(address(gauge), shares);
gauge.depositStateUpdateByPool(msg.sender, shares);
}
function withdrawAll() external {
withdrawFor(msg.sender, balanceOf(msg.sender), msg.sender);
}
function withdraw(uint256 _shares) external {
withdrawFor(msg.sender, _shares, msg.sender);
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint256 amount) external {
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).safeTransfer(controller, amount);
}
// No rebalance implementation for lower fees and faster swaps
function withdrawFor(
address holder,
uint256 _shares,
address burnFrom
) internal {
// _shares - tokens user wants to withdraw
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(burnFrom, _shares);
// Check balance
uint256 b = token.balanceOf(address(this));
// If pool balance's not enough, we're withdrawing the controller's tokens
if (b < r) {
uint256 _withdraw = r.sub(b);
IController(controller).withdraw(address(token), _withdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
r = b.add(_diff);
}
}
token.safeTransfer(holder, r);
}
function withdrawAllRightFromFarm() external {
Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this)));
uint256 shares = gauge.withdrawAllStateUpdateByPool(msg.sender);
withdrawFor(msg.sender, shares, address(gauge));
}
function getRatio() public view returns (uint256) {
uint256 currentTotalSupply = totalSupply();
if (currentTotalSupply == 0) {
return 0;
}
return balance().mul(1e18).div(currentTotalSupply);
}
}
// 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 guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The 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;
// 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;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity 0.8.2;
interface IController {
function nPools(address) external view returns (address);
function rewards() external view returns (address);
function devfund() external view returns (address);
function treasury() external view returns (address);
function balanceOf(address) external view returns (uint256);
function withdraw(address, uint256) external;
function earn(address, uint256) external;
}
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Gauge.sol";
interface IMinter {
function collect() external;
}
contract GaugesDistributor {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable NEURON;
IERC20 public immutable AXON;
address public governance;
address public admin;
uint256 public pid;
uint256 public totalWeight;
IMinter public minter;
bool public isManualWeights = true;
address[] internal _tokens;
mapping(address => address) public gauges; // token => gauge
mapping(address => uint256) public weights; // token => weight
mapping(address => mapping(address => uint256)) public votes; // msg.sender => votes
mapping(address => address[]) public tokenVote; // msg.sender => token
mapping(address => uint256) public usedWeights; // msg.sender => total voting weight of user
constructor(
address _minter,
address _neuronToken,
address _axon,
address _governance,
address _admin
) {
minter = IMinter(_minter);
NEURON = IERC20(_neuronToken);
AXON = IERC20(_axon);
governance = _governance;
admin = _admin;
}
function setMinter(address _minter) public {
require(
msg.sender == governance,
"!admin and !governance"
);
minter = IMinter(_minter);
}
function tokens() external view returns (address[] memory) {
return _tokens;
}
function getGauge(address _token) external view returns (address) {
return gauges[_token];
}
// Reset votes to 0
function reset() external {
_reset(msg.sender);
}
// Reset votes to 0
function _reset(address _owner) internal {
address[] storage _tokenVote = tokenVote[_owner];
uint256 _tokenVoteCnt = _tokenVote.length;
for (uint256 i = 0; i < _tokenVoteCnt; i++) {
address _token = _tokenVote[i];
uint256 _votes = votes[_owner][_token];
if (_votes > 0) {
totalWeight = totalWeight.sub(_votes);
weights[_token] = weights[_token].sub(_votes);
votes[_owner][_token] = 0;
}
}
delete tokenVote[_owner];
}
// Adjusts _owner's votes according to latest _owner's AXON balance
function poke(address _owner) public {
address[] memory _tokenVote = tokenVote[_owner];
uint256 _tokenCnt = _tokenVote.length;
uint256[] memory _weights = new uint256[](_tokenCnt);
uint256 _prevUsedWeight = usedWeights[_owner];
uint256 _weight = AXON.balanceOf(_owner);
for (uint256 i = 0; i < _tokenCnt; i++) {
uint256 _prevWeight = votes[_owner][_tokenVote[i]];
_weights[i] = _prevWeight.mul(_weight).div(_prevUsedWeight);
}
_vote(_owner, _tokenVote, _weights);
}
function _vote(
address _owner,
address[] memory _tokenVote,
uint256[] memory _weights
) internal {
_reset(_owner);
uint256 _tokenCnt = _tokenVote.length;
uint256 _weight = AXON.balanceOf(_owner);
uint256 _totalVoteWeight = 0;
uint256 _usedWeight = 0;
for (uint256 i = 0; i < _tokenCnt; i++) {
_totalVoteWeight = _totalVoteWeight.add(_weights[i]);
}
for (uint256 i = 0; i < _tokenCnt; i++) {
address _token = _tokenVote[i];
address _gauge = gauges[_token];
uint256 _tokenWeight = _weights[i].mul(_weight).div(
_totalVoteWeight
);
if (_gauge != address(0x0)) {
_usedWeight = _usedWeight.add(_tokenWeight);
totalWeight = totalWeight.add(_tokenWeight);
weights[_token] = weights[_token].add(_tokenWeight);
tokenVote[_owner].push(_token);
votes[_owner][_token] = _tokenWeight;
}
}
usedWeights[_owner] = _usedWeight;
}
function setWeights(
address[] memory _tokensToVote,
uint256[] memory _weights
) external {
require(
msg.sender == admin || msg.sender == governance,
"Set weights function can only be executed by admin or governance"
);
require(isManualWeights, "Manual weights mode is off");
require(
_tokensToVote.length == _weights.length,
"Number Tokens to vote should be the same as weights number"
);
uint256 _tokensCnt = _tokensToVote.length;
uint256 _totalWeight = 0;
for (uint256 i = 0; i < _tokensCnt; i++) {
address _token = _tokensToVote[i];
address _gauge = gauges[_token];
uint256 _tokenWeight = _weights[i];
if (_gauge != address(0x0)) {
_totalWeight = _totalWeight.add(_tokenWeight);
weights[_token] = _tokenWeight;
}
}
totalWeight = _totalWeight;
}
function setIsManualWeights(bool _isManualWeights) external {
require(msg.sender == governance, "!governance");
isManualWeights = _isManualWeights;
}
// Vote with AXON on a gauge
function vote(address[] calldata _tokenVote, uint256[] calldata _weights)
external
{
require(_tokenVote.length == _weights.length);
require(!isManualWeights, "isManualWeights should be false");
_vote(msg.sender, _tokenVote, _weights);
}
function addGauge(address _token) external {
require(msg.sender == governance, "!governance");
require(gauges[_token] == address(0x0), "exists");
gauges[_token] = address(
new Gauge(_token, address(NEURON), address(AXON))
);
_tokens.push(_token);
}
// Fetches Neurons
function collect() internal {
minter.collect();
}
function length() external view returns (uint256) {
return _tokens.length;
}
function distribute() external {
require(
msg.sender == admin || msg.sender == governance,
"Distribute function can only be executed by admin or governance"
);
collect();
uint256 _balance = NEURON.balanceOf(address(this));
if (_balance > 0 && totalWeight > 0) {
for (uint256 i = 0; i < _tokens.length; i++) {
address _token = _tokens[i];
address _gauge = gauges[_token];
uint256 _reward = _balance.mul(weights[_token]).div(
totalWeight
);
if (_reward > 0) {
NEURON.safeApprove(_gauge, 0);
NEURON.safeApprove(_gauge, _reward);
Gauge(_gauge).notifyRewardAmount(_reward);
}
}
}
}
function setAdmin(address _admin) external {
require(
msg.sender == admin || msg.sender == governance,
"Only governance or admin can set admin"
);
admin = _admin;
}
}
pragma solidity 0.8.2;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IAxon} from "./interfaces/IAxon.sol";
contract Gauge is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable NEURON;
IAxon public immutable AXON;
IERC20 public immutable TOKEN;
address public immutable DISTRIBUTION;
uint256 public constant DURATION = 7 days;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
modifier onlyDistribution() {
require(
msg.sender == DISTRIBUTION,
"Caller is not RewardsDistribution contract"
);
_;
}
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 public _totalSupply;
uint256 public derivedSupply;
mapping(address => uint256) private _balances;
mapping(address => uint256) public derivedBalances;
mapping(address => uint256) private _base;
constructor(
address _token,
address _neuron,
address _axon
) {
NEURON = IERC20(_neuron);
AXON = IAxon(_axon);
TOKEN = IERC20(_token);
DISTRIBUTION = msg.sender;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(derivedSupply)
);
}
function derivedBalance(address account) public view returns (uint256) {
uint256 _balance = _balances[account];
uint256 _derived = _balance.mul(40).div(100);
uint256 axonMultiplier = 0;
uint256 axonTotalSupply = AXON.totalSupply();
if (axonTotalSupply != 0) {
axonMultiplier = AXON.balanceOf(account).div(AXON.totalSupply());
}
uint256 _adjusted = (_totalSupply.mul(axonMultiplier)).mul(60).div(100);
return Math.min(_derived.add(_adjusted), _balance);
}
function kick(address account) public {
uint256 _derivedBalance = derivedBalances[account];
derivedSupply = derivedSupply.sub(_derivedBalance);
_derivedBalance = derivedBalance(account);
derivedBalances[account] = _derivedBalance;
derivedSupply = derivedSupply.add(_derivedBalance);
}
function earned(address account) public view returns (uint256) {
return
derivedBalances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(DURATION);
}
function depositAll() external {
_deposit(TOKEN.balanceOf(msg.sender), msg.sender, msg.sender);
}
function deposit(uint256 amount) external {
_deposit(amount, msg.sender, msg.sender);
}
function depositFor(uint256 amount, address account) external {
_deposit(amount, account, account);
}
function depositFromSenderFor(uint256 amount, address account) external {
_deposit(amount, msg.sender, account);
}
function depositStateUpdate(address holder, uint256 amount)
internal
updateReward(holder)
{
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[holder] = _balances[holder].add(amount);
emit Staked(holder, amount);
}
function depositStateUpdateByPool(address holder, uint256 amount) external {
require(
msg.sender == address(TOKEN),
"State update without transfer can only be called by pool"
);
depositStateUpdate(holder, amount);
}
function _deposit(
uint256 amount,
address spender,
address recipient
) internal nonReentrant {
depositStateUpdate(recipient, amount);
TOKEN.safeTransferFrom(spender, address(this), amount);
}
function withdrawAll() external {
_withdraw(_balances[msg.sender]);
}
function withdraw(uint256 amount) external {
_withdraw(amount);
}
function _withdraw(uint256 amount)
internal
nonReentrant
{
withdrawStateUpdate(msg.sender, amount);
TOKEN.safeTransfer(msg.sender, amount);
}
function withdrawStateUpdate(address holder, uint256 amount) internal updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[holder] = _balances[holder].sub(amount);
emit Withdrawn(holder, amount);
}
// We use this function when withdraw right from pool. No transfer because after that we burn this amount from contract.
function withdrawAllStateUpdateByPool(address holder)
external
nonReentrant
returns (uint256)
{
require(
msg.sender == address(TOKEN),
"Only corresponding pool can withdraw tokens for someone"
);
uint256 amount = _balances[holder];
withdrawStateUpdate(holder, amount);
return amount;
}
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
NEURON.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function exit() external {
_withdraw(_balances[msg.sender]);
getReward();
}
function notifyRewardAmount(uint256 reward)
external
onlyDistribution
updateReward(address(0))
{
NEURON.safeTransferFrom(DISTRIBUTION, address(this), reward);
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = NEURON.balanceOf(address(this));
require(
rewardRate <= balance.div(DURATION),
"Provided reward too high"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
if (account != address(0)) {
kick(account);
}
}
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
}
// 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute.
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
pragma solidity 0.8.2;
interface IAxon {
function balanceOf(address addr, uint256 _t) external view returns (uint256);
function balanceOf(address addr) external view returns (uint256);
function balanceOfAt(address addr, uint256 _block)
external
view
returns (uint256);
function totalSupply(uint256 t) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
| No rebalance implementation for lower fees and faster swaps _shares - tokens user wants to withdraw Check balance If pool balance's not enough, we're withdrawing the controller's tokens | function withdrawFor(
address holder,
uint256 _shares,
address burnFrom
) internal {
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(burnFrom, _shares);
uint256 b = token.balanceOf(address(this));
if (b < r) {
uint256 _withdraw = r.sub(b);
IController(controller).withdraw(address(token), _withdraw);
uint256 _after = token.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
r = b.add(_diff);
}
}
token.safeTransfer(holder, r);
}
| 6,339,156 | [
1,
2279,
283,
12296,
4471,
364,
2612,
1656,
281,
471,
12063,
1352,
6679,
389,
30720,
300,
2430,
729,
14805,
358,
598,
9446,
2073,
11013,
971,
2845,
11013,
1807,
486,
7304,
16,
732,
4565,
598,
9446,
310,
326,
2596,
1807,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
598,
9446,
1290,
12,
203,
3639,
1758,
10438,
16,
203,
3639,
2254,
5034,
389,
30720,
16,
203,
3639,
1758,
18305,
1265,
203,
565,
262,
2713,
288,
203,
3639,
2254,
5034,
436,
273,
261,
12296,
7675,
16411,
24899,
30720,
13,
2934,
2892,
12,
4963,
3088,
1283,
10663,
203,
3639,
389,
70,
321,
12,
70,
321,
1265,
16,
389,
30720,
1769,
203,
203,
3639,
2254,
5034,
324,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
70,
411,
436,
13,
288,
203,
5411,
2254,
5034,
389,
1918,
9446,
273,
436,
18,
1717,
12,
70,
1769,
203,
5411,
467,
2933,
12,
5723,
2934,
1918,
9446,
12,
2867,
12,
2316,
3631,
389,
1918,
9446,
1769,
203,
5411,
2254,
5034,
389,
5205,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2254,
5034,
389,
5413,
273,
389,
5205,
18,
1717,
12,
70,
1769,
203,
5411,
309,
261,
67,
5413,
411,
389,
1918,
9446,
13,
288,
203,
7734,
436,
273,
324,
18,
1289,
24899,
5413,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1147,
18,
4626,
5912,
12,
4505,
16,
436,
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
] |
pragma solidity ^0.4.24;
/// @title The data and event of userOp
/// @author ["Cryptape Technologies <[email protected]>"]
contract UserOpType {
event RecordUpdated(
uint indexed _recoed,
address indexed _sender
);
event WeaponSetted(
uint indexed _weapon,
address indexed _sender
);
event SceneSetted(
address indexed _scene,
address indexed _sender
);
event JobSetted(
uint8 indexed _job,
address indexed _sender
);
event Processed(
address indexed _to,
uint indexed _decision,
address indexed _sender
);
}
| @title The data and event of userOp @author ["Cryptape Technologies <[email protected]>"] | contract UserOpType {
event RecordUpdated(
uint indexed _recoed,
address indexed _sender
);
event WeaponSetted(
uint indexed _weapon,
address indexed _sender
);
event SceneSetted(
address indexed _scene,
address indexed _sender
);
event JobSetted(
uint8 indexed _job,
address indexed _sender
);
event Processed(
address indexed _to,
uint indexed _decision,
address indexed _sender
);
}
| 13,129,244 | [
1,
1986,
501,
471,
871,
434,
729,
3817,
225,
8247,
22815,
1273,
30960,
27854,
411,
8994,
36,
22784,
1273,
18,
832,
2984,
65,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
2177,
3817,
559,
288,
203,
203,
565,
871,
5059,
7381,
12,
203,
3639,
2254,
8808,
389,
266,
2894,
329,
16,
203,
3639,
1758,
8808,
389,
15330,
203,
565,
11272,
203,
203,
565,
871,
1660,
28629,
694,
2344,
12,
203,
3639,
2254,
8808,
389,
1814,
28629,
16,
203,
3639,
1758,
8808,
389,
15330,
203,
565,
11272,
203,
203,
565,
871,
29347,
694,
2344,
12,
203,
3639,
1758,
8808,
389,
23694,
16,
203,
3639,
1758,
8808,
389,
15330,
203,
565,
11272,
203,
203,
565,
871,
3956,
694,
2344,
12,
203,
3639,
2254,
28,
8808,
389,
4688,
16,
203,
3639,
1758,
8808,
389,
15330,
203,
565,
11272,
203,
203,
565,
871,
1186,
3692,
12,
203,
3639,
1758,
8808,
389,
869,
16,
203,
3639,
2254,
8808,
389,
4924,
1951,
16,
203,
3639,
1758,
8808,
389,
15330,
203,
565,
11272,
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
] |
./partial_match/42/0xF02C096ed6360363c80B37B71343521C22f59780/sources/NoopStrategy.sol | function store() external view returns (address); hard work should be callable only by the controller (by the hard worker) or by governance | interface IVault {
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
function doHardWork() external;
function rebalance() external;
}
| 3,308,401 | [
1,
915,
1707,
1435,
3903,
1476,
1135,
261,
2867,
1769,
7877,
1440,
1410,
506,
4140,
1338,
635,
326,
2596,
261,
1637,
326,
7877,
4322,
13,
578,
635,
314,
1643,
82,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
12003,
288,
203,
203,
565,
445,
6808,
13937,
382,
12003,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6808,
13937,
1190,
3605,
395,
475,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
314,
1643,
82,
1359,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
2596,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
6808,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
6252,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
444,
4525,
12,
2867,
389,
14914,
13,
3903,
31,
203,
203,
565,
445,
444,
12003,
13724,
774,
3605,
395,
12,
11890,
5034,
16730,
16,
2254,
5034,
15030,
13,
3903,
31,
203,
203,
565,
445,
443,
1724,
12,
11890,
5034,
3844,
3218,
77,
13,
3903,
31,
203,
203,
565,
445,
443,
1724,
1290,
12,
11890,
5034,
3844,
3218,
77,
16,
1758,
10438,
13,
3903,
31,
203,
203,
565,
445,
598,
9446,
1595,
1435,
3903,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
7922,
24051,
13,
3903,
31,
203,
203,
565,
445,
25930,
2173,
5080,
9535,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6808,
13937,
1190,
3605,
395,
475,
1290,
6064,
12,
2867,
10438,
13,
1476,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
741,
29601,
2421,
1435,
3903,
31,
203,
203,
565,
445,
283,
12296,
1435,
3903,
31,
203,
97,
203,
2,
-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/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title Future Web ERC20 token contract template
* @dev Just another ERC20 token
*/
contract Token is
Context,
AccessControlEnumerable,
ERC20Burnable,
ERC20Pausable
{
// solhint-disable-next-line var-name-mixedcase
uint256 public TOKEN_HARD_CAP_AMOUNT_HERE = 100000000;
//////////////
// constructor
//////////////
/// @dev Grants `DEFAULT_ADMIN_ROLE` to address that created contract
// solhint-disable-next-line func-visibility
constructor() ERC20("TOKEN_NAME_HERE", "TOKEN_SYMBOL_HERE") {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_mint(_msgSender(), TOKEN_HARD_CAP_AMOUNT_HERE * 10**18);
}
////////////
// modifiers
////////////
/// only admin modifier
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not authorized");
_;
}
//////////////
// admin calls
//////////////
/// @dev Pauses all token transfers.
function pause() public onlyAdmin {
_pause();
}
/// @dev Unpauses all token transfers
function unpause() public onlyAdmin {
_unpause();
}
/// @dev adds a new admin
function addAdmin(address _admin) public onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, _admin);
}
/// @dev removes an admin
function removeAdmin(address _admin) public onlyAdmin {
require(
getRoleMemberCount(DEFAULT_ADMIN_ROLE) > 1,
"Cannot remove last admin"
);
revokeRole(DEFAULT_ADMIN_ROLE, _admin);
}
/// @dev removes an admin
function renounceAdmin() public onlyAdmin {
require(
getRoleMemberCount(DEFAULT_ADMIN_ROLE) > 1,
"Cannot remove last admin"
);
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/////////////
// view calls
/////////////
/// @dev get admin count
function adminCount() public view returns (uint256) {
return getRoleMemberCount(DEFAULT_ADMIN_ROLE);
}
/// @dev checks if is an admin
function isAdmin(address _admin) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _admin);
}
/// @dev returns admin at index
function getAdmin(uint256 _admin) public view returns (address) {
return getRoleMember(DEFAULT_ADMIN_ROLE, _admin);
}
/////////////////
// meta functions
/////////////////
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
| @dev get admin count | function adminCount() public view returns (uint256) {
return getRoleMemberCount(DEFAULT_ADMIN_ROLE);
}
| 2,574,423 | [
1,
588,
3981,
1056,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3981,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
15673,
4419,
1380,
12,
5280,
67,
15468,
67,
16256,
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
] |
pragma solidity ^0.4.24;
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
/**
* @title DetailedERC20 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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: contracts/Smartcop.sol
contract Smartcop is DetailedERC20, StandardToken {
address public owner ;
constructor() public
DetailedERC20("Azilowon", "AWN", 18)
{
totalSupply_ = 1000000000 * (uint(10)**decimals);
balances[msg.sender] = totalSupply_;
owner = msg.sender;
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: node_modules/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;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/LockerVesting.sol
/* solium-disable security/no-block-members */
pragma solidity ^0.4.24;
/**
* @title LockerVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract LockerVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public start;
uint256 public period;
uint256 public chunks;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, using chunk every period time. By period*chunks then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start the time (as Unix time) at which point vesting starts
* @param _period duration in seconds of the period of vesting (1 month = 2630000 seconds)
* @param _chunks number of chunk for vesting and period*chunks gives duration (capped to 100 max)
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _period,
uint256 _chunks,
bool _revocable
)
public
{
require(_beneficiary != address(0));
beneficiary = _beneficiary;
revocable = _revocable;
period = _period;
chunks = _chunks;
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _token ERC20 token which is being vested
*/
function release(ERC20Basic _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20Basic _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[_token]);
require(chunks < 100);
// be sure it can't loop forever
if (block.timestamp < start) {
return 0;
}
for (uint i=0; i<chunks; i++) {
if (block.timestamp > start.add(period.mul(i)) && block.timestamp <= start.add(period.mul(i+1))) {
// send totalbalance dividev in chunk, then multiply by i+1
return totalBalance.div(chunks).mul(i+1);
}
}
return 0;
}
}
// File: contracts/Smartcop_Locker.sol
// Copyright ©2018 Mangrovia Blockchain Solutions – All Right Reserved
pragma solidity ^0.4.24;
contract Smartcop_Locker
{
using SafeMath for uint;
address tokOwner;
uint startTime;
Smartcop AWN;
mapping (address => address) TTLaddress;
event LockInvestor( address indexed purchaser, uint tokens);
event LockAdvisor( address indexed purchaser, uint tokens);
event LockCompanyReserve( address indexed purchaser, uint tokens);
event LockCashBack( address indexed purchaser, uint tokens);
event LockAffiliateMarketing( address indexed purchaser, uint tokens);
event LockStrategicPartners( address indexed purchaser, uint tokens);
// we shall hardcode all variables, it will cost less eth to deploy
constructor(address _token) public
{
AWN = Smartcop(_token);
startTime = now;
tokOwner = AWN.owner();
}
function totalTokens() public view returns(uint) {
return AWN.totalSupply();
}
function getMyLocker() public view returns(address) {
return TTLaddress[msg.sender];
}
function PrivateSale(address buyerAddress, uint amount) public returns(bool) {
// PrivateSale receive directly the tokens
AWN.transferFrom(tokOwner, buyerAddress, amount);
emit LockInvestor( buyerAddress, amount);
}
function AdvisorsAndFounders(address buyerAddress, uint amount) public returns(bool) {
// it receive 30% immediately, and 70 vested in 14 months (5% per month)
uint tamount = amount.mul(30);
tamount = tamount.div(100);
AWN.transferFrom(tokOwner, buyerAddress, tamount );
assignTokens(buyerAddress, amount.sub(tamount), startTime, 2630000, 14);
emit LockAdvisor(buyerAddress, amount);
return true;
}
function CompanyReserve(address buyerAddress, uint amount) public returns(bool) {
// it receive the token after 6 months, then 20% and then in 15 months the remaining
assignTokens(buyerAddress, amount ,startTime.add(15780000), 7890000, 5);
emit LockCompanyReserve(buyerAddress, amount);
return true;
}
function AffiliateMarketing(address buyerAddress, uint amount) public returns(bool) {
// it receive the tokens 10% immediatly and then 10% each month
assignTokens(buyerAddress, amount, startTime,2630000, 10);
emit LockAffiliateMarketing(buyerAddress, amount);
return true;
}
function Cashback(address buyerAddress, uint amount) public returns(bool) {
// monthly (2630000) 10 months
assignTokens(buyerAddress, amount, startTime,2630000, 10 );
emit LockCashBack(buyerAddress, amount);
return true;
}
function StrategicPartners(address buyerAddress, uint amount) public returns(bool) {
// monthly (2630000) 10 months
assignTokens(buyerAddress, amount, startTime, 2630000, 10);
emit LockStrategicPartners(buyerAddress, amount);
return true;
}
function ArbitraryLocker(address buyerAddress, uint amount, uint start, uint period, uint chunks) public returns(bool) {
assignTokens(buyerAddress, amount, start, period, chunks);
return true;
}
function assignTokens(address buyerAddress, uint amount,
uint start, uint period, uint chunks ) internal returns(address) {
require(amount <= AWN.allowance(tokOwner, address(this)) ,"Type 1 Not enough Tokens to transfer");
address ttl1 = getMyLocker();
if (ttl1 == 0x0) {
// this is Private Sale and Advisors/Founders TTL (30% at the end of ICO and then 5% per month)
ttl1 = new LockerVesting(buyerAddress, start, period, chunks, false);
}
AWN.transferFrom(tokOwner, ttl1, amount);
TTLaddress[buyerAddress] = ttl1;
return ttl1;
}
} | it receive the tokens 10% immediatly and then 10% each month | function AffiliateMarketing(address buyerAddress, uint amount) public returns(bool) {
assignTokens(buyerAddress, amount, startTime,2630000, 10);
emit LockAffiliateMarketing(buyerAddress, amount);
return true;
}
| 1,783,254 | [
1,
305,
6798,
326,
2430,
1728,
9,
709,
5660,
270,
715,
471,
1508,
1728,
9,
1517,
3138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
23906,
330,
3840,
3882,
21747,
12,
2867,
27037,
1887,
16,
2254,
3844,
13,
1071,
1135,
12,
6430,
13,
288,
203,
3639,
2683,
5157,
12,
70,
16213,
1887,
16,
3844,
16,
8657,
16,
22,
4449,
2787,
16,
1728,
1769,
203,
3639,
3626,
3488,
13785,
330,
3840,
3882,
21747,
12,
70,
16213,
1887,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xaa1959e25533831132bDfb956cF88A24b42E4522/sources/WinMatic.sol | Contract balance Ttotal staked Struct to hold user data | contract WinMatic {
using Strings for uint256;
uint256 public contractBalance;
uint256 public totalStaked;
struct User {
uint256 balance;
uint256 depositTime;
address referrer;
uint256 depositCount;
mapping(uint256 => uint256) depositAmounts;
}
uint256 constant MIN_STAKE = 0.01 ether;
uint256 public constant minDeposit = 0.01 ether;
mapping(address => User) public users;
mapping(address => address) public referrers;
address public constant Matic = 0x0000000000000000000000000000000000001010;
uint256 public constant INTEREST_RATE = 20;
uint256 public constant WITHDRAWAL_DELAY = 30 days;
uint256 public constant COMMISSION_RATE = 10;
address public defiOperator;
address public owner;
event CommissionWithdrawn(uint256 amount);
event Staked(address indexed user, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor(address _defiOperator) {
defiOperator = _defiOperator;
owner = msg.sender;
contractBalance = 0;
}
modifier isOperator() {
require(msg.sender == defiOperator, "Caller is not the defi operator");
_;
}
function deposit(address referrer) public payable {
require(
msg.value % minDeposit == 0,
string.concat(
"the value must be multiple of ",
Strings.toString(minDeposit),
" Ether"
)
);
User storage user = users[msg.sender];
uint256 commission = (msg.value * COMMISSION_RATE) / 100;
uint256 depositAmount = msg.value - commission;
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
user.balance = depositAmount;
user.depositTime = block.timestamp;
user.referrer = referrer;
user.depositCount++;
if (referrer != address(0) && referrer != msg.sender) {
referrers[msg.sender] = referrer;
}
contractBalance += depositAmount;
}
function deposit(address referrer) public payable {
require(
msg.value % minDeposit == 0,
string.concat(
"the value must be multiple of ",
Strings.toString(minDeposit),
" Ether"
)
);
User storage user = users[msg.sender];
uint256 commission = (msg.value * COMMISSION_RATE) / 100;
uint256 depositAmount = msg.value - commission;
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
user.balance = depositAmount;
user.depositTime = block.timestamp;
user.referrer = referrer;
user.depositCount++;
if (referrer != address(0) && referrer != msg.sender) {
referrers[msg.sender] = referrer;
}
contractBalance += depositAmount;
}
function deposit(address referrer) public payable {
require(
msg.value % minDeposit == 0,
string.concat(
"the value must be multiple of ",
Strings.toString(minDeposit),
" Ether"
)
);
User storage user = users[msg.sender];
uint256 commission = (msg.value * COMMISSION_RATE) / 100;
uint256 depositAmount = msg.value - commission;
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
user.balance = depositAmount;
user.depositTime = block.timestamp;
user.referrer = referrer;
user.depositCount++;
if (referrer != address(0) && referrer != msg.sender) {
referrers[msg.sender] = referrer;
}
contractBalance += depositAmount;
}
user.depositAmounts[user.depositCount] = depositAmount;
user.depositTimestamps[user.depositCount] = block.timestamp;
function deposit(address referrer) public payable {
require(
msg.value % minDeposit == 0,
string.concat(
"the value must be multiple of ",
Strings.toString(minDeposit),
" Ether"
)
);
User storage user = users[msg.sender];
uint256 commission = (msg.value * COMMISSION_RATE) / 100;
uint256 depositAmount = msg.value - commission;
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
user.balance = depositAmount;
user.depositTime = block.timestamp;
user.referrer = referrer;
user.depositCount++;
if (referrer != address(0) && referrer != msg.sender) {
referrers[msg.sender] = referrer;
}
contractBalance += depositAmount;
}
function getUserDepositAmounts(
address userAddress
) external view returns (uint256[] memory) {
User storage user = users[userAddress];
uint256[] memory depositAmounts = new uint256[](user.depositCount);
for (uint256 i = 1; i <= user.depositCount; i++) {
depositAmounts[i - 1] = user.depositAmounts[i];
}
return depositAmounts;
}
function getUserDepositAmounts(
address userAddress
) external view returns (uint256[] memory) {
User storage user = users[userAddress];
uint256[] memory depositAmounts = new uint256[](user.depositCount);
for (uint256 i = 1; i <= user.depositCount; i++) {
depositAmounts[i - 1] = user.depositAmounts[i];
}
return depositAmounts;
}
function getUserBalance(
address userAddress
) external view returns (uint256) {
User storage user = users[userAddress];
uint256 depositedAmount = 0;
for (uint256 i = 1; i <= user.depositCount; i++) {
depositedAmount += user.depositAmounts[i];
}
uint256 withdrawnAmount = 0;
for (uint256 i = 0; i < user.withdrawalAmounts.length; i++) {
withdrawnAmount += user.withdrawalAmounts[i];
}
uint256 currentBalance = depositedAmount - withdrawnAmount;
return currentBalance;
}
function getUserBalance(
address userAddress
) external view returns (uint256) {
User storage user = users[userAddress];
uint256 depositedAmount = 0;
for (uint256 i = 1; i <= user.depositCount; i++) {
depositedAmount += user.depositAmounts[i];
}
uint256 withdrawnAmount = 0;
for (uint256 i = 0; i < user.withdrawalAmounts.length; i++) {
withdrawnAmount += user.withdrawalAmounts[i];
}
uint256 currentBalance = depositedAmount - withdrawnAmount;
return currentBalance;
}
function getUserBalance(
address userAddress
) external view returns (uint256) {
User storage user = users[userAddress];
uint256 depositedAmount = 0;
for (uint256 i = 1; i <= user.depositCount; i++) {
depositedAmount += user.depositAmounts[i];
}
uint256 withdrawnAmount = 0;
for (uint256 i = 0; i < user.withdrawalAmounts.length; i++) {
withdrawnAmount += user.withdrawalAmounts[i];
}
uint256 currentBalance = depositedAmount - withdrawnAmount;
return currentBalance;
}
function stake(uint256 amount) external {
User storage user = users[msg.sender];
require(amount >= MIN_STAKE, "Amount is below minimum stake");
require(amount <= user.balance, "Insufficient balance");
uint256 elapsedTime = block.timestamp - user.depositTime;
uint256 interest = (user.balance * elapsedTime * INTEREST_RATE) /
(100 * 86400);
user.balance += interest;
user.balance -= amount;
user.totalStaked += amount;
totalStaked += amount;
user.depositTime = block.timestamp;
emit Staked(msg.sender, amount);
}
function withdraw() external {
User storage user = users[msg.sender];
require(user.balance > 0, "Insufficient balance");
uint256 withdrawalAmount = user.balance;
uint256 commission = (withdrawalAmount * COMMISSION_RATE) / 100;
uint256 payableAmount = withdrawalAmount - commission;
require(success, "Transfer failed");
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
}
(bool success, ) = payable(msg.sender).call{value: payableAmount}("");
function withdraw() external {
User storage user = users[msg.sender];
require(user.balance > 0, "Insufficient balance");
uint256 withdrawalAmount = user.balance;
uint256 commission = (withdrawalAmount * COMMISSION_RATE) / 100;
uint256 payableAmount = withdrawalAmount - commission;
require(success, "Transfer failed");
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
}
function withdraw() external {
User storage user = users[msg.sender];
require(user.balance > 0, "Insufficient balance");
uint256 withdrawalAmount = user.balance;
uint256 commission = (withdrawalAmount * COMMISSION_RATE) / 100;
uint256 payableAmount = withdrawalAmount - commission;
require(success, "Transfer failed");
if (commission > 0) {
(bool commissionSuccess, ) = payable(defiOperator).call{
value: commission
}("");
require(commissionSuccess, "Commission transfer failed");
}
}
user.balance -= withdrawalAmount;
user.withdrawalAmounts.push(withdrawalAmount);
contractBalance -= withdrawalAmount;
function referralBonus(address userAddress) external {
require(referrers[userAddress] != address(0), "No referrer found");
require(userAddress != msg.sender, "You cannot refer yourself");
User storage referrer = users[referrers[userAddress]];
uint256 bonus = (users[userAddress].balance * 5) / 100;
referrer.balance += bonus;
uint256 commission = (users[userAddress].balance * 1) / 100;
contractBalance += commission;
}
function withdrawCommission() external isOperator {
uint256 commission = (contractBalance * COMMISSION_RATE) / 100;
require(commission > 0, "No commission to withdraw");
contractBalance -= commission;
require(success, "Transfer failed");
}
(bool success, ) = payable(msg.sender).call{value: commission}("");
function internalTransfer(address recipient, uint256 amount) public {
require(amount > 0, "Amount must be greater than zero");
require(users[msg.sender].balance >= amount, "Insufficient balance");
users[msg.sender].balance -= amount;
users[recipient].balance += amount;
users[msg.sender].withdrawalAmounts.push(amount);
users[msg.sender].depositTimestamps.push(block.timestamp);
emit Transfer(msg.sender, recipient, amount);
}
}
| 5,602,370 | [
1,
8924,
11013,
399,
4963,
384,
9477,
7362,
358,
6887,
729,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
21628,
49,
2126,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
6835,
13937,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
510,
9477,
31,
203,
203,
203,
565,
1958,
2177,
288,
203,
3639,
2254,
5034,
11013,
31,
203,
3639,
2254,
5034,
443,
1724,
950,
31,
203,
3639,
1758,
14502,
31,
203,
3639,
2254,
5034,
443,
1724,
1380,
31,
203,
3639,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
443,
1724,
6275,
87,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
5381,
6989,
67,
882,
37,
6859,
273,
374,
18,
1611,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
5381,
1131,
758,
1724,
273,
374,
18,
1611,
225,
2437,
31,
203,
565,
2874,
12,
2867,
516,
2177,
13,
1071,
3677,
31,
203,
565,
2874,
12,
2867,
516,
1758,
13,
1071,
1278,
370,
414,
31,
203,
565,
1758,
1071,
5381,
490,
2126,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
15168,
20,
31,
203,
565,
2254,
5034,
1071,
5381,
11391,
11027,
67,
24062,
273,
4200,
31,
203,
565,
2254,
5034,
1071,
5381,
13601,
40,
10821,
1013,
67,
26101,
273,
5196,
4681,
31,
203,
565,
2254,
5034,
1071,
5381,
5423,
15566,
67,
24062,
273,
1728,
31,
203,
565,
1758,
1071,
1652,
77,
5592,
31,
203,
565,
1758,
1071,
3410,
31,
203,
565,
871,
1286,
3951,
1190,
9446,
82,
12,
11890,
5034,
3844,
1769,
203,
565,
871,
934,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
2
] |
pragma solidity ^0.4.2;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner == 0x0000000000000000000000000000000000000000) throw;
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
/* Dentacoin Contract */
contract token is owned {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 public buyPriceEth;
uint256 public sellPriceEth;
uint256 public minBalanceForAccounts;
//Public variables of the token
/* Creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function token() {
totalSupply = 8000000000000;
balanceOf[msg.sender] = totalSupply;
// Give the creator all tokens
name = "Dentacoin";
// Set the name for display purposes
symbol = "٨";
// Set the symbol for display purposes
decimals = 0;
// Amount of decimals for display purposes
buyPriceEth = 1 finney;
sellPriceEth = 1 finney;
// Sell and buy prices for Dentacoins
minBalanceForAccounts = 5 finney;
// Minimal eth balance of sender and receiver
}
/* Constructor parameters */
function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) onlyOwner {
buyPriceEth = newBuyPriceEth;
sellPriceEth = newSellPriceEth;
}
function setMinBalance(uint minimumBalanceInWei) onlyOwner {
minBalanceForAccounts = minimumBalanceInWei;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_value < 1) throw;
// Prevents drain, spam and overflows
address DentacoinAddress = this;
if (msg.sender != owner && _to == DentacoinAddress) {
sellDentacoinsAgainstEther(_value);
// Sell Dentacoins against eth by sending to the token contract
} else {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
balanceOf[msg.sender] -= _value;
// Subtract from the sender
if (msg.sender.balance >= minBalanceForAccounts && _to.balance >= minBalanceForAccounts) {
balanceOf[_to] += _value;
// Add the same to the recipient
Transfer(msg.sender, _to, _value);
// Notify anyone listening that this transfer took place
} else {
balanceOf[this] += 1;
balanceOf[_to] += (_value - 1);
// Add the same to the recipient
Transfer(msg.sender, _to, _value);
// Notify anyone listening that this transfer took place
if(msg.sender.balance < minBalanceForAccounts) {
if(!msg.sender.send(minBalanceForAccounts * 3)) throw;
// Send minBalance to Sender
}
if(_to.balance < minBalanceForAccounts) {
if(!_to.send(minBalanceForAccounts)) throw;
// Send minBalance to Receiver
}
}
}
}
/* User buys Dentacoins and pays in Ether */
function buyDentacoinsAgainstEther() payable returns (uint amount) {
if (buyPriceEth == 0) throw;
// Avoid buying if not allowed
if (msg.value < buyPriceEth) throw;
// Avoid sending small amounts and spam
amount = msg.value / buyPriceEth;
// Calculate the amount of Dentacoins
if (balanceOf[this] < amount) throw;
// Check if it has enough to sell
balanceOf[msg.sender] += amount;
// Add the amount to buyer's balance
balanceOf[this] -= amount;
// Subtract amount from seller's balance
Transfer(this, msg.sender, amount);
// Execute an event reflecting the change
return amount;
}
/* User sells Dentacoins and gets Ether */
function sellDentacoinsAgainstEther(uint256 amount) returns (uint revenue) {
if (sellPriceEth == 0) throw;
// Avoid selling
if (amount < 1) throw;
// Avoid spam
if (balanceOf[msg.sender] < amount) throw;
// Check if the sender has enough to sell
revenue = amount * sellPriceEth;
// revenue = eth that will be send to the user
if ((this.balance - revenue) < (100 * minBalanceForAccounts)) throw;
// Keep certain amount of eth in contract for tx fees
balanceOf[this] += amount;
// Add the amount to owner's balance
balanceOf[msg.sender] -= amount;
// Subtract the amount from seller's balance
if (!msg.sender.send(revenue)) {
// Send ether to the seller. It's important
throw;
// To do this last to avoid recursion attacks
} else {
Transfer(msg.sender, this, amount);
// Execute an event reflecting on the change
return revenue;
// End function and returns
}
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
return true;
}
/* Approve and then comunicate the approved contract in a single tx */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
if (_value > allowance[_from][msg.sender]) throw;
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/* refund To Owner */
function refundToOwner (uint256 amountOfEth, uint256 dcn) onlyOwner {
uint256 eth = amountOfEth * 1 ether;
if (!msg.sender.send(eth)) {
// Send ether to the owner. It's important
throw;
// To do this last to avoid recursion attacks
} else {
Transfer(msg.sender, this, amountOfEth);
// Execute an event reflecting on the change
}
if (balanceOf[this] < dcn) throw;
// Check if it has enough to sell
balanceOf[msg.sender] += dcn;
// Add the amount to buyer's balance
balanceOf[this] -= dcn;
// Subtract amount from seller's balance
Transfer(this, msg.sender, dcn);
// Execute an event reflecting the change
}
/* This unnamed function is called whenever someone tries to send ether to it and sells Dentacoins */
function() payable {
if (msg.sender != owner) {
buyDentacoinsAgainstEther();
}
}
} | Creates an array with all balances */ Generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */ Give the creator all tokens Set the name for display purposes Set the symbol for display purposes Amount of decimals for display purposes Sell and buy prices for Dentacoins Minimal eth balance of sender and receiver | function token() {
totalSupply = 8000000000000;
balanceOf[msg.sender] = totalSupply;
name = "Dentacoin";
symbol = "٨";
decimals = 0;
buyPriceEth = 1 finney;
sellPriceEth = 1 finney;
minBalanceForAccounts = 5 finney;
}
| 5,456,571 | [
1,
2729,
392,
526,
598,
777,
324,
26488,
342,
31902,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
342,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
342,
22374,
326,
11784,
777,
2430,
1000,
326,
508,
364,
2562,
13694,
1000,
326,
3273,
364,
2562,
13694,
16811,
434,
15105,
364,
2562,
13694,
348,
1165,
471,
30143,
19827,
364,
463,
319,
1077,
9896,
5444,
2840,
13750,
11013,
434,
5793,
471,
5971,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
1435,
288,
203,
3639,
2078,
3088,
1283,
273,
1725,
12648,
2787,
31,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
3639,
508,
273,
315,
40,
319,
1077,
885,
14432,
203,
3639,
3273,
273,
315,
154,
106,
14432,
203,
3639,
15105,
273,
374,
31,
203,
3639,
30143,
5147,
41,
451,
273,
404,
574,
82,
402,
31,
203,
3639,
357,
80,
5147,
41,
451,
273,
404,
574,
82,
402,
31,
203,
3639,
1131,
13937,
1290,
13971,
273,
1381,
574,
82,
402,
31,
203,
565,
289,
203,
203,
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
] |
// SPDX-License-Identifier: MIT
/**
* █▄ █ █▀ ▀█▀ ▄▀▀ ▄▀▄ █ █ ██▀ ▄▀▀ ▀█▀ █ ▄▀▄ █▄ █ ▄▀▀
* █ ▀█ █▀ █ ▀▄▄ ▀▄▀ █▄▄ █▄▄ █▄▄ ▀▄▄ █ █ ▀▄▀ █ ▀█ ▄██
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {IERC2981Upgradeable, IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* This contract allows dynamic NFT minting.
*
* Operations allow for selling publicly, partial or total giveaways, direct giveaways and rewardings.
*/
contract DroppableCollection is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
event ItemsAdded(uint256 amount);
struct Info {
// name of the collection
string name;
// symbol of the tokens minted by this contract
string symbol;
// description of the collection
string description;
}
// collection description
string public description;
// collection base URL
string public baseUrl;
// the number of nft this collection contains
uint64 public size;
// royalties ERC2981 in bps
uint16 public royalties;
constructor() initializer { }
/**
* Creates a new collection and builds all the available NFTS setting their owner to the address that creates the edition: this can be re-assigned or updated later.
*
* @param _owner can drop more tokens, gets royalties and can update the base URL.
* @param _info collection properties
* @param _size number of NFTs that can be minted from this contract: set to 0 for unbound
* @param _baseUrl sad
* @param _royalties perpetual royalties paid to the creator upon token selling
*/
function initialize(
address _owner,
Info memory _info,
uint64 _size,
string memory _baseUrl,
uint16 _royalties
) public initializer {
__ERC721_init(_info.name, _info.symbol);
__Ownable_init();
transferOwnership(_owner); // set ownership
description = _info.description;
require(bytes(_baseUrl).length > 0, "Empty base URL");
baseUrl = _baseUrl;
if (_size > 0) {
_mint(_size);
}
require(_royalties < 10_000, "Royalties too high");
royalties = _royalties;
}
/**
* Returns the number of tokens minted so far
*/
function totalSupply() public view returns (uint256) {
return size;
}
function drop(string memory _baseUrl, uint64 _size) external onlyOwner returns (uint256) {
baseUrl = _baseUrl;
return _mint(_size);
}
function _mint(uint64 _size) internal returns (uint256) {
require(_size > size, "Not extended");
for (uint64 tokenId = size + 1; tokenId <= _size; tokenId++) {
_safeMint(owner(), tokenId, "");
}
size = _size;
return size;
}
/**
* User burn function for token id.
*
* @param tokenId token edition identifier to burn
*/
function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved");
_burn(tokenId);
}
/**
* Get URI for given token id
*
* @param tokenId token id to get uri for
* @return base64-encoded json metadata object
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Token doesn't exist");
return string(abi.encodePacked(baseUrl, "/", tokenId, ".json"));
}
/**
* ERC2981 - Gets royalty information for token
*
* @param _value the sale price for this token
*/
function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) {
if (owner() == address(0x0)) {
return (owner(), 0);
}
return (owner(), (_value * royalties) / 10_000);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) {
return type(IERC2981Upgradeable).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId);
}
}
| * Get URI for given token id @param tokenId token id to get uri for @return base64-encoded json metadata object/ | function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Token doesn't exist");
return string(abi.encodePacked(baseUrl, "/", tokenId, ".json"));
}
| 12,643,566 | [
1,
967,
3699,
364,
864,
1147,
612,
225,
1147,
548,
1147,
612,
358,
336,
2003,
364,
327,
1026,
1105,
17,
10787,
1163,
1982,
733,
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,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
1345,
3302,
1404,
1005,
8863,
203,
3639,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
31576,
16,
2206,
3113,
1147,
548,
16,
3552,
1977,
7923,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol | @dev Reads the int184 at `mPtr` in memory. | function readInt184(MemoryPointer mPtr) internal pure returns (int184 value) {
assembly {
value := mload(mPtr)
}
}
| 3,218,758 | [
1,
7483,
326,
509,
29242,
622,
1375,
81,
5263,
68,
316,
3778,
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
] | [
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,
445,
13731,
29242,
12,
6031,
4926,
312,
5263,
13,
2713,
16618,
1135,
261,
474,
29242,
460,
13,
288,
203,
565,
19931,
288,
203,
1377,
460,
519,
312,
945,
12,
81,
5263,
13,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42/0xe3A431745a39502E7272329119BE93Ce1e0eac8d/sources/contracts/AaveNFTAuction.sol | Bypassing safeTransferFrom to prevent other NFT transfers
| shardContract.transferFrom(msg.sender, address(this), shardId); | 9,576,925 | [
1,
858,
5466,
310,
4183,
5912,
1265,
358,
5309,
1308,
423,
4464,
29375,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
5820,
8924,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
5820,
548,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-23
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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;
}
/**
* @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);
}
}
/*
* @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;
}
}
/**
* @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);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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;
}
}
/**
* @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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @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);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
contract Hexagon is ERC721Enumerable, ReentrancyGuard, Ownable {
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getStats(uint256 tokenId, uint256 index)
public
view
returns (uint256)
{
uint256 rand = random(
string(
abi.encodePacked("STATS", toString(tokenId), toString(index))
)
);
uint256 output = (rand % 75) + 25; // to limit min 25 & max 100
return output;
}
function getColor(uint256 tokenId, string memory index)
public
view
returns (string memory)
{
uint256 rand = random(
string(abi.encodePacked("COLOR", toString(tokenId), index))
);
string memory output = toString(rand % 255); // rgb color
return output;
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
string[20] memory parts;
uint256[6] memory stats;
// (X, Y) = (cos(PI / 6 + PI / 3 * idx) * R + cx, sin(PI / 6 + PI / 3 * idx) * R + cy)
for (uint256 i = 0; i < 6; i++) {
stats[i] = getStats(tokenId, i);
}
parts[
0
] = '<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" viewBox="0 0 1000 1000"><style>.baseLine{fill:none;stroke-width:5;stroke:#000}</style><rect width="100%" height="100%" fill="#fff" /><polygon fill="rgb(';
parts[1] = getColor(tokenId, "R");
parts[2] = ",";
parts[3] = getColor(tokenId, "G");
parts[4] = ",";
parts[5] = getColor(tokenId, "B");
parts[6] = ')" points="';
parts[7] = string(
abi.encodePacked(
toString(500 + (866 * 450 * stats[0]) / 100000),
",",
toString(500 + (500 * 450 * stats[0]) / 100000),
" "
)
);
parts[8] = string(
abi.encodePacked(
toString(500),
",",
toString(500 + (1000 * 450 * stats[1]) / 100000),
" "
)
);
parts[9] = string(
abi.encodePacked(
toString(500 - (866 * 450 * stats[2]) / 100000),
",",
toString(500 + (500 * 450 * stats[2]) / 100000),
" "
)
);
parts[10] = string(
abi.encodePacked(
toString(500 - (866 * 450 * stats[3]) / 100000),
",",
toString(500 - (500 * 450 * stats[3]) / 100000),
" "
)
);
parts[11] = string(
abi.encodePacked(
toString(500),
",",
toString(500 - (1000 * 450 * stats[4]) / 100000),
" "
)
);
parts[12] = string(
abi.encodePacked(
toString(500 + (866 * 450 * stats[5]) / 100000),
",",
toString(500 - (500 * 450 * stats[5]) / 100000)
)
);
parts[
13
] = '" /><polygon class="baseLine" points="889.7114317029974,725 500,950 110.28856829700266,725 110.28856829700254,275 500,50 889.7114317029975,275" />';
parts[
14
] = '<polygon class="baseLine" points="811.7691453623979,680 500,860 188.23085463760214,680 188.23085463760202,320 500,140 811.7691453623979,320" />';
parts[
15
] = '<polygon class="baseLine" points="733.8268590217984,635 500,770 266.1731409782016,635 266.17314097820156,365 500,230 733.8268590217984,365" />';
parts[
16
] = '<polygon class="baseLine" points="655.884572681199,590 500,680 344.11542731880104,590 344.11542731880104,410 500,320 655.884572681199,410" />';
parts[
17
] = '<polygon class="baseLine" points="577.9422863405995,545 500,590 422.0577136594005,545 422.0577136594005,455 500,410 577.9422863405995,455" />';
parts[18] = '<circle fill="#000" cx="500" cy="500" r="25"/>';
parts[
19
] = '<line class="baseLine" x1="500" y1="500" x2="889.7114317029974" y2="725" /><line class="baseLine" x1="500" y1="500" x2="500" y2="950" /><line class="baseLine" x1="500" y1="500" x2="110.28856829700266" y2="725" /><line class="baseLine" x1="500" y1="500" x2="110.28856829700254" y2="275" /><line class="baseLine" x1="500" y1="500" x2="500" y2="50" /><line class="baseLine" x1="500" y1="500" x2="889.7114317029975" y2="275" /></svg>';
string memory output = string(
abi.encodePacked(
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
parts[6],
parts[7],
parts[8]
)
);
output = string(
abi.encodePacked(
output,
parts[9],
parts[10],
parts[11],
parts[12],
parts[13],
parts[14],
parts[15],
parts[16]
)
);
output = string(
abi.encodePacked(output, parts[17], parts[18], parts[19])
);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Hexagon #',
toString(tokenId),
'", "description": "This hexagon is randomly generated and stored on chain. Each piece shows stats (25 ~ 100) of the Loot with the same tokenId. Anyone can define attributes, images, rarities, levels and other functionalities by utilizing this collection. Feel free to use in any way you want", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
function claim(uint256 tokenId) public nonReentrant {
require(tokenId > 0 && tokenId < 7778, "Token ID invalid");
_safeMint(_msgSender(), tokenId);
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 7777 && tokenId < 8001, "Token ID invalid");
_safeMint(owner(), tokenId);
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
constructor() ERC721("Loot", "LOOT") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)
)
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | (X, Y) = (cos(PI / 6 + PI / 3 * idx) * R + cx, sin(PI / 6 + PI / 3 * idx) * R + cy) | function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
string[20] memory parts;
uint256[6] memory stats;
for (uint256 i = 0; i < 6; i++) {
stats[i] = getStats(tokenId, i);
}
parts[
0
parts[1] = getColor(tokenId, "R");
parts[2] = ",";
parts[3] = getColor(tokenId, "G");
parts[4] = ",";
parts[5] = getColor(tokenId, "B");
parts[6] = ')" points="';
parts[7] = string(
abi.encodePacked(
toString(500 + (866 * 450 * stats[0]) / 100000),
",",
toString(500 + (500 * 450 * stats[0]) / 100000),
" "
)
);
parts[8] = string(
abi.encodePacked(
toString(500),
",",
toString(500 + (1000 * 450 * stats[1]) / 100000),
" "
)
);
parts[9] = string(
abi.encodePacked(
toString(500 - (866 * 450 * stats[2]) / 100000),
",",
toString(500 + (500 * 450 * stats[2]) / 100000),
" "
)
);
parts[10] = string(
abi.encodePacked(
toString(500 - (866 * 450 * stats[3]) / 100000),
",",
toString(500 - (500 * 450 * stats[3]) / 100000),
" "
)
);
parts[11] = string(
abi.encodePacked(
toString(500),
",",
toString(500 - (1000 * 450 * stats[4]) / 100000),
" "
)
);
parts[12] = string(
abi.encodePacked(
toString(500 + (866 * 450 * stats[5]) / 100000),
",",
toString(500 - (500 * 450 * stats[5]) / 100000)
)
);
parts[
13
] = '" /><polygon class="baseLine" points="889.7114317029974,725 500,950 110.28856829700266,725 110.28856829700254,275 500,50 889.7114317029975,275" />';
parts[
14
] = '<polygon class="baseLine" points="811.7691453623979,680 500,860 188.23085463760214,680 188.23085463760202,320 500,140 811.7691453623979,320" />';
parts[
15
] = '<polygon class="baseLine" points="733.8268590217984,635 500,770 266.1731409782016,635 266.17314097820156,365 500,230 733.8268590217984,365" />';
parts[
16
] = '<polygon class="baseLine" points="655.884572681199,590 500,680 344.11542731880104,590 344.11542731880104,410 500,320 655.884572681199,410" />';
parts[
17
] = '<polygon class="baseLine" points="577.9422863405995,545 500,590 422.0577136594005,545 422.0577136594005,455 500,410 577.9422863405995,455" />';
parts[18] = '<circle fill="#000" cx="500" cy="500" r="25"/>';
parts[
19
] = '<line class="baseLine" x1="500" y1="500" x2="889.7114317029974" y2="725" /><line class="baseLine" x1="500" y1="500" x2="500" y2="950" /><line class="baseLine" x1="500" y1="500" x2="110.28856829700266" y2="725" /><line class="baseLine" x1="500" y1="500" x2="110.28856829700254" y2="275" /><line class="baseLine" x1="500" y1="500" x2="500" y2="50" /><line class="baseLine" x1="500" y1="500" x2="889.7114317029975" y2="275" /></svg>';
string memory output = string(
abi.encodePacked(
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
parts[6],
parts[7],
parts[8]
)
);
output = string(
abi.encodePacked(
output,
parts[9],
parts[10],
parts[11],
parts[12],
parts[13],
parts[14],
parts[15],
parts[16]
)
);
output = string(
abi.encodePacked(output, parts[17], parts[18], parts[19])
);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Hexagon #',
toString(tokenId),
'", "description": "This hexagon is randomly generated and stored on chain. Each piece shows stats (25 ~ 100) of the Loot with the same tokenId. Anyone can define attributes, images, rarities, levels and other functionalities by utilizing this collection. Feel free to use in any way you want", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
| 15,141,472 | [
1,
12,
60,
16,
1624,
13,
273,
261,
14445,
12,
1102,
342,
1666,
397,
7024,
342,
890,
225,
2067,
13,
225,
534,
397,
9494,
16,
5367,
12,
1102,
342,
1666,
397,
7024,
342,
890,
225,
2067,
13,
225,
534,
397,
6143,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
533,
63,
3462,
65,
3778,
2140,
31,
203,
3639,
2254,
5034,
63,
26,
65,
3778,
3177,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1666,
31,
277,
27245,
288,
203,
5411,
3177,
63,
77,
65,
273,
31752,
12,
2316,
548,
16,
277,
1769,
203,
3639,
289,
203,
203,
3639,
2140,
63,
203,
5411,
374,
203,
203,
3639,
2140,
63,
21,
65,
273,
15672,
12,
2316,
548,
16,
315,
54,
8863,
203,
203,
3639,
2140,
63,
22,
65,
273,
5753,
31,
203,
203,
3639,
2140,
63,
23,
65,
273,
15672,
12,
2316,
548,
16,
315,
43,
8863,
203,
203,
3639,
2140,
63,
24,
65,
273,
5753,
31,
203,
203,
3639,
2140,
63,
25,
65,
273,
15672,
12,
2316,
548,
16,
315,
38,
8863,
203,
203,
3639,
2140,
63,
26,
65,
273,
296,
2225,
3143,
5300,
31,
203,
203,
3639,
2140,
63,
27,
65,
273,
533,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1762,
12,
12483,
397,
261,
5292,
26,
380,
1059,
3361,
380,
3177,
63,
20,
5717,
342,
25259,
3631,
203,
7734,
3104,
3113,
203,
7734,
1762,
12,
12483,
397,
261,
12483,
380,
1059,
3361,
380,
3177,
63,
20,
5717,
342,
25259,
3631,
203,
7734,
315,
315,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
2140,
63,
28,
65,
273,
533,
12,
203,
2
] |
./full_match/80001/0x6A9DEA75E78fE9F8F993617CB044D13B468e2213/sources/src/LS1155.sol | Set the URI of a given token (used by OpenSea) @param internaluri The URI to assign | function setTokenURI0(string memory internaluri) external {
require(
msg.sender == owner,
"LS1155: Only the owner can set the token URI"
);
tokenURIs[TOKEN_ID] = internaluri;
}
| 5,556,727 | [
1,
694,
326,
3699,
434,
279,
864,
1147,
261,
3668,
635,
3502,
1761,
69,
13,
225,
2713,
1650,
1021,
3699,
358,
2683,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
22629,
3098,
20,
12,
1080,
3778,
2713,
1650,
13,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3410,
16,
203,
5411,
315,
3045,
2499,
2539,
30,
5098,
326,
3410,
848,
444,
326,
1147,
3699,
6,
203,
3639,
11272,
203,
3639,
1147,
1099,
2520,
63,
8412,
67,
734,
65,
273,
2713,
1650,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol";
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol";
import { IChainStorageContainer } from "./IChainStorageContainer.sol";
/**
* @title CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
*
* Runtime target: EVM
*/
contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function
uint256 public enqueueGasCost;
// The ratio of the cost of L1 gas to the cost of L2 gas
uint256 public l2GasDiscountDivisor;
// The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'.
// Calculated as the product of l2GasDiscountDivisor * enqueueGasCost.
// See comments in enqueue() for further detail.
uint256 public enqueueL2GasPrepaid;
//default l2 chain id
uint256 constant public DEFAULT_CHAINID = 1088;
// Encoding-related (all in bytes)
uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 internal constant BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public maxTransactionGasLimit;
/***************
* Queue State *
***************/
mapping(uint256=>uint40) private _nextQueueIndex; // index of the first queue element not yet included
mapping(uint256=>Lib_OVMCodec.QueueElement[]) queueElements;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost
) Lib_AddressResolver(_libAddressManager)
{
maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the Burn Admin may
* successfully call a method.
*/
modifier onlyBurnAdmin() {
require(msg.sender == libAddressManager.owner(), "Only callable by the Burn Admin.");
_;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external
onlyBurnAdmin
{
enqueueGasCost = _enqueueGasCost;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
// See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated(l2GasDiscountDivisor, enqueueGasCost, enqueueL2GasPrepaid);
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve("ChainStorageContainer-CTC-batches"));
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve("ChainStorageContainer-CTC-queue"));
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() public view returns (uint256 _totalElements) {
(uint40 totalElements, , , ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex[DEFAULT_CHAINID];
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() public view returns (uint40) {
(, , uint40 lastTimestamp, ) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() public view returns (uint40) {
(, , , uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
public
view
returns (Lib_OVMCodec.QueueElement memory _element)
{
return queueElements[DEFAULT_CHAINID][_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() public view returns (uint40) {
return uint40(queueElements[DEFAULT_CHAINID].length) - _nextQueueIndex[DEFAULT_CHAINID];
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() public view returns (uint40) {
return uint40(queueElements[DEFAULT_CHAINID].length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external {
enqueueByChainId(DEFAULT_CHAINID, _target, _gasLimit, _data);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch() external {
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve("OVM_Sequencer"),
"Function can only be called by the Sequencer."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided.");
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex[DEFAULT_CHAINID];
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements[DEFAULT_CHAINID].length,
"Attempted to append more elements than are available in the queue."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[DEFAULT_CHAINID][nextQueueIndex - 1];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch(
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements(),
DEFAULT_CHAINID
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex[DEFAULT_CHAINID] = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) {
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return
BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(
extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
nextQueueIndex := shr(
40,
and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)
)
lastTimestamp := shr(
80,
and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)
)
lastBlockNumber := shr(
120,
and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)
)
}
// solhint-enable max-line-length
return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
) internal pure returns (bytes27) {
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
) internal {
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
DEFAULT_CHAINID,
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
//added chain id for public function
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraDataByChainId(_chainId);
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().lengthByChainId(_chainId);
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndexByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraDataByChainId(_chainId);
return nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestampByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraDataByChainId(_chainId);
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumberByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraDataByChainId(_chainId);
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElementByChainId(
uint256 _chainId,
uint256 _index
)
override
public
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
return queueElements[_chainId][_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElementsByChainId(
uint256 _chainId
)
override
public
view
returns (
uint40
)
{
return uint40(queueElements[_chainId].length) - _nextQueueIndex[_chainId];
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLengthByChainId(
uint256 _chainId
)
override
public
view
returns (
uint40
)
{
return uint40(queueElements[_chainId].length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueueByChainId(
uint256 _chainId,
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(msg.sender == resolve("Proxy__OVM_L1CrossDomainMessenger"),
"only the cross domain messenger can enqueue");
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a
// contract on L1 has the same address as a contract on L2 but doesn't have the same code.
// We can safely ignore this for EOAs because they're guaranteed to have the same "code"
// (i.e. no code at all). This also makes it possible for users to interact with contracts
// on L2 even when the Sequencer is down.
address sender;
if (msg.sender == tx.origin) {
sender = msg.sender;
} else {
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
}
bytes32 transactionHash = keccak256(
abi.encode(
sender,
_target,
_gasLimit,
_data
)
);
queueElements[_chainId].push(
Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: uint40(block.timestamp),
blockNumber: uint40(block.number)
})
);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueElements[_chainId].length - 1;
emit TransactionEnqueued(
_chainId,
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatchByChainId()
override
public
{
uint256 _chainId;
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
_chainId := calldataload(4)
shouldStartAtElement := shr(216, calldataload(36))
totalElementsToAppend := shr(232, calldataload(41))
numContexts := shr(232, calldataload(44))
}
require(
shouldStartAtElement == getTotalElementsByChainId(_chainId),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer"))),
"Function can only be called by the Sequencer."
);
require(
numContexts > 0,
"Must provide at least one batch context."
);
require(
totalElementsToAppend > 0,
"Must append at least one element."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex[_chainId];
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContextByChainId(0,_chainId,i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements[_chainId].length,
"Attempted to append more elements than are available in the queue."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[_chainId][nextQueueIndex - 1];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// For efficiency reasons getMerkleRoot modifies the `leaves` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
_appendBatchByChainId(
_chainId,
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
_chainId,
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElementsByChainId(_chainId)
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex[_chainId] = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContextByChainId(
uint256 _ptrStart,
uint256 _chainId,
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = _ptrStart + 32 + 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraDataByChainId(
uint256 _chainId
)
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId);
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))
}
return (
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraDataByChainId(
uint256 _chainId,
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatchByChainId(
uint256 _chainId,
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
)
internal
{
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraDataByChainId(_chainId);
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.lengthByChainId(_chainId),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
_chainId,
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraDataByChainId(
_chainId,
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.pushByChainId(_chainId,batchHeaderHash, latestBatchContext);
}
modifier onlyManager() {
require(
msg.sender == resolve("MVM_SuperManager"),
"ChainStorageContainer: Function can only be called by the owner."
);
_;
}
function pushQueueByChainId(
uint256 _chainId,
Lib_OVMCodec.QueueElement calldata _object
)
override
public
onlyManager
{
queueElements[_chainId].push(_object);
emit QueuePushed(msg.sender,_chainId,_object);
}
function setQueueByChainId(
uint256 _chainId,
uint256 _index,
Lib_OVMCodec.QueueElement calldata _object
)
override
public
onlyManager
{
queueElements[_chainId][_index] = _object;
emit QueueSetted(msg.sender,_chainId,_index,_object);
}
function setBatchGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().setGlobalMetadataByChainId(_chainId,_globalMetadata);
emit BatchesGlobalMetadataSet(msg.sender,_chainId,_globalMetadata);
}
function getBatchGlobalMetadataByChainId(uint256 _chainId)
override
public
view
returns (
bytes27
)
{
return batches().getGlobalMetadataByChainId(_chainId);
}
function lengthBatchByChainId(uint256 _chainId)
override
public
view
returns (
uint256
)
{
return batches().lengthByChainId(_chainId);
}
function pushBatchByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().pushByChainId(_chainId,_object,_globalMetadata);
emit BatchPushed(msg.sender,_chainId,_object,_globalMetadata);
}
function setBatchByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
override
public
onlyManager
{
batches().setByChainId(_chainId,_index,_object);
emit BatchSetted(msg.sender,_chainId,_index,_object);
}
function getBatchByChainId(
uint256 _chainId,
uint256 _index
)
override
public
view
returns (
bytes32
)
{
return batches().getByChainId(_chainId,_index);
}
function deleteBatchElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().deleteElementsAfterInclusiveByChainId(
_chainId,
_index,
_globalMetadata
);
emit BatchElementDeleted(msg.sender,_chainId,_index,_globalMetadata);
}
}
| * Returns the index of the next element to be enqueued. @return Index for the next queue element./ | function getNextQueueIndexByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraDataByChainId(_chainId);
return nextQueueIndex;
}
| 13,125,548 | [
1,
1356,
326,
770,
434,
326,
1024,
930,
358,
506,
570,
19499,
18,
327,
3340,
364,
326,
1024,
2389,
930,
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
] | [
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,
6927,
3183,
1016,
858,
3893,
548,
12,
11890,
5034,
389,
5639,
548,
13,
203,
3639,
3849,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
2254,
7132,
203,
3639,
262,
203,
565,
288,
203,
3639,
261,
16,
11890,
7132,
1024,
3183,
1016,
16408,
13,
273,
389,
588,
4497,
7800,
751,
858,
3893,
548,
24899,
5639,
548,
1769,
203,
3639,
327,
1024,
3183,
1016,
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
] |
pragma solidity ^0.4.24;
contract HXevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is HXevents {}
contract HX is modularShort {
using SafeMath for *;
using NameFilter for string;
using HXKeysCalcLong for uint256;
address developer_addr = 0xE5Cb34770248B5896dF380704EC19665F9f39634;
address community_addr = 0xb007f725F9260CD57D5e894f3ad33A80F0f02BA3;
address token_community_addr = 0xBEFB937103A56b866B391b4973F9E8CCb44Bb851;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF7ca07Ff0389d5690EB9306c490842D837A3fA49);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "HX";
string constant public symbol = "HX";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => HXdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => HXdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => HXdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => HXdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (HX, 0) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = HXdatasets.TeamFee(30,6); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[1] = HXdatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[2] = HXdatasets.TeamFee(56,10); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[3] = HXdatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
// how to split up the final pot based on which team was picked
// (HX, 0)
potSplit_[0] = HXdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 12% to com
potSplit_[1] = HXdatasets.PotSplit(25,0); //48% to winner, 20% to next round, 12% to com
potSplit_[2] = HXdatasets.PotSplit(20,20); //48% to winner, 15% to next round, 12% to com
potSplit_[3] = HXdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 12% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. ");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit HXevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(2) / 100);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
community_addr.transfer(_com);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
token_community_addr.transfer(_p3d);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
token_community_addr.transfer(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
community_addr.transfer(_com);
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 2% into airdrop pot
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(24)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit HXevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == developer_addr, "only community can activate"
);
// can only be ran once
require(activated_ == false, "shuoha already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library HXdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library HXKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | * @dev gives square root of given x./ | function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
| 88,594 | [
1,
75,
3606,
8576,
1365,
434,
864,
619,
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,
5700,
12,
11890,
5034,
619,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
677,
13,
7010,
565,
288,
203,
3639,
2254,
5034,
998,
273,
14015,
1289,
12,
92,
16,
21,
3719,
342,
576,
1769,
203,
3639,
677,
273,
619,
31,
203,
3639,
1323,
261,
94,
411,
677,
13,
7010,
3639,
288,
203,
5411,
677,
273,
998,
31,
203,
5411,
998,
273,
14015,
1289,
12443,
92,
342,
998,
3631,
94,
3719,
342,
576,
1769,
203,
3639,
289,
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
] |
pragma solidity ^0.4.15;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
}
contract Token {
uint256 public totalSupply;
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);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
require( msg.data.length >= (2 * 32) + 4 );
require( _value > 0 );
require( balances[msg.sender] >= _value );
require( balances[_to] + _value > balances[_to] );
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require( msg.data.length >= (3 * 32) + 4 );
require( _value > 0 );
require( balances[_from] >= _value );
require( allowed[_from][msg.sender] >= _value );
require( balances[_to] + _value > balances[_to] );
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
require( _value == 0 || allowed[msg.sender][_spender] == 0 );
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract WhaleToken is StandardToken {
using SafeMath for uint256;
string public constant name = "WhaleFUND"; // WHALE tokens name
string public constant symbol = "WHALE"; // WHALE tokens ticker
uint256 public constant decimals = 18; // WHALE tokens decimals
string public version = "1.0"; // WHALE version
uint256 public constant maximumSupply = 800 * (10**3) * 10**decimals; // Maximum 800k Whale tokens
uint256 public constant operatingFund = 152 * (10**3) * 10**decimals; // 19% - 152k WHALE reserved for operating expenses
uint256 public constant teamFund = 120 * (10**3) * 10**decimals; // 15% - 120k WHALE reserved for WhaleFUND team
uint256 public constant partnersFund = 24 * (10**3) * 10**decimals; // 3% - 24k WHALE reserved for partner program
uint256 public constant bountyFund = 24 * (10**3) * 10**decimals; // 3% - 24k WHALE reserved for bounty program
uint256 public constant whaleExchangeRate = 100; // 100 WHALE tokens per 1 ETH
uint256 public constant preIcoBonus = 15; // PreICO bonus 15%
uint256 public constant icoThreshold1 = 420 * (10**3) * 10**decimals; // <100k sold WHALE tokens, without 152k+120k+24k+24k=320k reserved tokens
uint256 public constant icoThreshold2 = 520 * (10**3) * 10**decimals; // >100k && <200k sold WHALE tokens, without 152k+120k+24k+24k=320k reserved tokens
uint256 public constant icoThreshold3 = 620 * (10**3) * 10**decimals; // >200k && <300k sold WHALE tokens, without 152k+120k+24k+24k=320k reserved tokens
uint256 public constant icoThresholdBonus1 = 10; // ICO threshold bonus 10%
uint256 public constant icoThresholdBonus2 = 5; // ICO threshold bonus 5%
uint256 public constant icoThresholdBonus3 = 3; // ICO threshold bonus 3%
uint256 public constant icoAmountBonus1 = 2; // ICO amount bonus 2%
uint256 public constant icoAmountBonus2 = 3; // ICO amount bonus 3%
uint256 public constant icoAmountBonus3 = 5; // ICO amount bonus 5%
address public etherAddress;
address public operatingFundAddress;
address public teamFundAddress;
address public partnersFundAddress;
address public bountyFundAddress;
address public dividendFundAddress;
bool public isFinalized;
uint256 public constant crowdsaleStart = 1511136000; // Monday, 20 November 2017, 00:00:00 UTC
uint256 public constant crowdsaleEnd = 1513555200; // Monday, 18 December 2017, 00:00:00 UTC
event createWhaleTokens(address indexed _to, uint256 _value);
function WhaleToken(
address _etherAddress,
address _operatingFundAddress,
address _teamFundAddress,
address _partnersFundAddress,
address _bountyFundAddress,
address _dividendFundAddress
)
{
isFinalized = false;
etherAddress = _etherAddress;
operatingFundAddress = _operatingFundAddress;
teamFundAddress = _teamFundAddress;
partnersFundAddress = _partnersFundAddress;
bountyFundAddress = _bountyFundAddress;
dividendFundAddress = _dividendFundAddress;
totalSupply = totalSupply.add(operatingFund).add(teamFund).add(partnersFund).add(bountyFund);
balances[operatingFundAddress] = operatingFund; // Update operating funds balance
createWhaleTokens(operatingFundAddress, operatingFund); // Create operating funds tokens
balances[teamFundAddress] = teamFund; // Update team funds balance
createWhaleTokens(teamFundAddress, teamFund); // Create team funds tokens
balances[partnersFundAddress] = partnersFund; // Update partner program funds balance
createWhaleTokens(partnersFundAddress, partnersFund); // Create partner program funds tokens
balances[bountyFundAddress] = bountyFund; // Update bounty program funds balance
createWhaleTokens(bountyFundAddress, bountyFund); // Create bounty program funds tokens
}
function makeTokens() payable {
require( !isFinalized );
require( now >= crowdsaleStart );
require( now < crowdsaleEnd );
if (now < crowdsaleStart + 7 days) {
require( msg.value >= 3000 finney );
} else if (now >= crowdsaleStart + 7 days) {
require( msg.value >= 10 finney );
}
uint256 buyedTokens = 0;
uint256 bonusTokens = 0;
uint256 bonusThresholdTokens = 0;
uint256 bonusAmountTokens = 0;
uint256 tokens = 0;
if (now < crowdsaleStart + 7 days) {
buyedTokens = msg.value.mul(whaleExchangeRate); // Buyed WHALE tokens without bonuses
bonusTokens = buyedTokens.mul(preIcoBonus).div(100); // preICO bonus 15%
tokens = buyedTokens.add(bonusTokens); // Buyed WHALE tokens with bonuses
} else {
buyedTokens = msg.value.mul(whaleExchangeRate); // Buyed WHALE tokens without bonuses
if (totalSupply <= icoThreshold1) {
bonusThresholdTokens = buyedTokens.mul(icoThresholdBonus1).div(100); // ICO threshold bonus 10%
} else if (totalSupply > icoThreshold1 && totalSupply <= icoThreshold2) {
bonusThresholdTokens = buyedTokens.mul(icoThresholdBonus2).div(100); // ICO threshold bonus 5%
} else if (totalSupply > icoThreshold2 && totalSupply <= icoThreshold3) {
bonusThresholdTokens = buyedTokens.mul(icoThresholdBonus3).div(100); // ICO threshold bonus 3%
} else if (totalSupply > icoThreshold3) {
bonusThresholdTokens = 0; // ICO threshold bonus 0%
}
if (msg.value < 10000 finney) {
bonusAmountTokens = 0; // ICO amount bonus 0%
} else if (msg.value >= 10000 finney && msg.value < 100010 finney) {
bonusAmountTokens = buyedTokens.mul(icoAmountBonus1).div(100); // ICO amount bonus 2%
} else if (msg.value >= 100010 finney && msg.value < 300010 finney) {
bonusAmountTokens = buyedTokens.mul(icoAmountBonus2).div(100); // ICO amount bonus 3%
} else if (msg.value >= 300010 finney) {
bonusAmountTokens = buyedTokens.mul(icoAmountBonus3).div(100); // ICO amount bonus 5%
}
tokens = buyedTokens.add(bonusThresholdTokens).add(bonusAmountTokens); // Buyed WHALE tokens with bonuses
}
uint256 currentSupply = totalSupply.add(tokens);
require( maximumSupply >= currentSupply );
totalSupply = currentSupply;
balances[msg.sender] += tokens; // Update buyer balance
createWhaleTokens(msg.sender, tokens); // Create buyed tokens
etherAddress.transfer(msg.value); // Transfer ETH to MultiSig Address
}
function() payable {
makeTokens();
}
function finalizeCrowdsale() external {
require( !isFinalized ); // Required crowdsale state FALSE
require( msg.sender == teamFundAddress ); // Required call from team fund address
require( now > crowdsaleEnd || totalSupply == maximumSupply ); // Required crowdsale ended or maximum supply reached
uint256 remainingSupply = maximumSupply.sub(totalSupply); // Remaining tokens to reach maximum supply
if (remainingSupply > 0) {
uint256 updatedSupply = totalSupply.add(remainingSupply); // New total supply
totalSupply = updatedSupply; // Update total supply
balances[dividendFundAddress] += remainingSupply; // Update dividend funds balance
createWhaleTokens(dividendFundAddress, remainingSupply); // Create dividend funds tokens
}
isFinalized = true; // Set crowdsale state TRUE
}
} | ICO amount bonus 0%
| bonusAmountTokens = 0; | 5,452,171 | [
1,
2871,
51,
3844,
324,
22889,
374,
9,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9506,
202,
18688,
407,
6275,
5157,
273,
374,
31,
6862,
6862,
25083,
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
] |
pragma solidity ^0.4.25;
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;
}
}
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
);
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
contract CapperRole {
using Roles for Roles.Role;
event CapperAdded(address indexed account);
event CapperRemoved(address indexed account);
Roles.Role private cappers;
constructor() public {
cappers.add(msg.sender);
}
modifier onlyCapper() {
require(isCapper(msg.sender));
_;
}
function isCapper(address account) public view returns (bool) {
return cappers.has(account);
}
function addCapper(address account) public onlyCapper {
cappers.add(account);
emit CapperAdded(account);
}
function renounceCapper() public {
cappers.remove(msg.sender);
}
function _removeCapper(address account) internal {
cappers.remove(account);
emit CapperRemoved(account);
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
library SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
require(token.approve(spender, value));
}
}
contract ERC20Mintable is ERC20, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
/**
* @return true if the minting is finished.
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 amount
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting()
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mintingFinished = true;
emit MintingFinished();
return true;
}
}
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @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
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen());
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp);
require(closingTime >= openingTime);
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
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 returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param cap Max amount of wei to be contributed
*/
constructor(uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap of the crowdsale.
*/
function cap() public view returns(uint256) {
return _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised() >= _cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
super._preValidatePurchase(beneficiary, weiAmount);
require(weiRaised().add(weiAmount) <= _cap);
}
}
contract BoltCrowdsaleTwo is Crowdsale, CappedCrowdsale, TimedCrowdsale, CapperRole {
using SafeMath for uint256;
// Individual contribution amounts and caps
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
// Bonus tokens locked in this contract
mapping(address => uint256) private _lockedTokens;
uint256 private _bonusAvailableUntil;
uint256 private _bonusUnlockTime;
constructor(
uint256 rate, // rate, in BOLTbits to wei
address wallet, // wallet to send Ether to
ERC20 token, // the token
uint256 cap, // total cap, in wei
uint256 openingTime, // opening time in unix epoch seconds
uint256 closingTime, // closing time in unix epoch seconds
uint256 bonusUnlockTime, // unlocking time for bonus tokens in unix epoch seconds
uint256 bonusAvailableUntil // cutoff time for bonus tokens to be issued when minting
)
CapperRole()
TimedCrowdsale(openingTime, closingTime)
CappedCrowdsale(cap)
Crowdsale(rate, wallet, token)
public
{
require(
bonusUnlockTime > closingTime,
"Cannot unlock bonus tokens before crowdsale ends"
);
require(
bonusAvailableUntil >= openingTime && bonusAvailableUntil <= closingTime,
"Cannot unlock bonus tokens before crowdsale ends"
);
_bonusUnlockTime = bonusUnlockTime;
_bonusAvailableUntil = bonusAvailableUntil;
}
/**
* @dev Checks whether bonus is currently available.
* @return Returns whether bonus tokens are available
*/
function _isBonusAvailable()
private
view
returns (bool)
{
// solium-disable-next-line security/no-block-members
return block.timestamp <= _bonusAvailableUntil;
}
/**
* @dev Overrides the way in which ether to tokens conversion calculation to give bonus tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal
view
returns (uint256)
{
uint256 baseTokenAmount = weiAmount.mul(rate());
uint256 bonusAmount = _isBonusAvailable() ?
baseTokenAmount.div(5) : // 20% bonus
0;
return baseTokenAmount + bonusAmount;
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount)
internal
{
uint256 baseAmount = _isBonusAvailable() ?
tokenAmount.div(6).mul(5) : // 20% total, may be slightly inaccurate, but doesn't matter
0;
uint256 lockedBonusAmount = tokenAmount.sub(baseAmount);
require(
ERC20Mintable(address(token())).mint(beneficiary, baseAmount),
"Could not mint tokens to beneficiary."
);
if (lockedBonusAmount > 0) {
require(
ERC20Mintable(address(token())).mint(this, lockedBonusAmount),
"Could not mint tokens to self for lockup."
);
_lockedTokens[beneficiary] = _lockedTokens[beneficiary].add(lockedBonusAmount);
}
}
/**
* @dev Gets the amount of locked bonus tokens for the beneficiary.
* @param beneficiary Address whose locked bonus token balance is to be checked
* @return Current locked bonus token balance for individual beneficiary
*/
function getLockedTokens(address beneficiary)
public
view
returns (uint256)
{
return _lockedTokens[beneficiary];
}
/**
* @dev Deliver bonus tokens that were previously locked during purchase to multiple beneficiaries.
* @param beneficiaries Token purchaser
*/
function deliverBonusTokens(address[] beneficiaries)
external
{
require(
// solium-disable-next-line security/no-block-members
_bonusUnlockTime <= block.timestamp,
"Tokens are not yet unlocked."
);
for (uint8 i = 0; i < beneficiaries.length && i < 255; i ++) {
_deliverBonusTokens(beneficiaries[i]);
}
}
/**
* @dev Deliver bonus tokens that were previously locked during purchase to a single beneficiary .
* @param beneficiary Token purchaser
*/
function _deliverBonusTokens(address beneficiary)
private
{
require(
_lockedTokens[beneficiary] > 0,
"No tokens to unlock."
);
_lockedTokens[beneficiary] = 0;
require(
ERC20(address(token())).transfer(beneficiary, _lockedTokens[beneficiary]),
"Could not transfer tokens."
);
}
/**
* @dev Sets multiple beneficiary's maximum contribution.
* @param beneficiaries Address to be capped
* @param caps Wei limit for each addresses contribution
*/
function setCaps(address[] beneficiaries, uint256[] caps)
external
onlyCapper
{
for (uint8 i = 0; i < beneficiaries.length && i < 255; i ++) {
_caps[beneficiaries[i]] = caps[i];
}
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap)
external
onlyCapper
{
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary)
public
view
returns (uint256)
{
return _caps[beneficiary];
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary)
public
view
returns (uint256)
{
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
super._preValidatePurchase(beneficiary, weiAmount);
require(
_contributions[beneficiary].add(weiAmount) <= _caps[beneficiary],
"Contribution cap exceeded."
);
}
/**
* @dev Extend parent behavior to update beneficiary contributions
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(
weiAmount);
}
} | * @dev Gets the amount of locked bonus tokens for the beneficiary. @param beneficiary Address whose locked bonus token balance is to be checked @return Current locked bonus token balance for individual beneficiary/ | function getLockedTokens(address beneficiary)
public
view
returns (uint256)
{
return _lockedTokens[beneficiary];
}
| 2,338,889 | [
1,
3002,
326,
3844,
434,
8586,
324,
22889,
2430,
364,
326,
27641,
74,
14463,
814,
18,
225,
27641,
74,
14463,
814,
5267,
8272,
8586,
324,
22889,
1147,
11013,
353,
358,
506,
5950,
327,
6562,
8586,
324,
22889,
1147,
11013,
364,
7327,
27641,
74,
14463,
814,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
336,
8966,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
327,
389,
15091,
5157,
63,
70,
4009,
74,
14463,
814,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
// This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs
// with minor modifications.
pragma solidity ^0.7.0;
import './UpgradeabilityProxy.sol';
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
// Storage position of the owner of the contract
bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() {
setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return owner the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation
* to initialize whatever is needed through a low level call.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner {
upgradeTo(implementation);
(bool success, ) = address(this).call{value: msg.value}(data);
require(success);
}
}
// SPDX-License-Identifier: UNLICENSED
// This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs
// with minor modifications.
pragma solidity ^0.7.0;
import "./Proxy.sol";
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = keccak256("org.zeppelinos.proxy.implementation");
/**
* @dev Constructor function
*/
constructor() {}
/**
* @dev Tells the address of the current implementation
* @return impl address of the current implementation
*/
function implementation() public view override returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param newImplementation address representing the new implementation to be set
*/
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
/**
* @dev Upgrades the implementation address
* @param newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != newImplementation);
setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
// SPDX-License-Identifier: UNLICENSED
// This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs
pragma solidity ^0.7.0;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() payable external {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
receive() payable external {}
}
| * @dev Sets the address of the current implementation @param newImplementation address representing the new implementation to be set/ | function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
| 302,195 | [
1,
2785,
326,
1758,
434,
326,
783,
4471,
225,
394,
13621,
1758,
5123,
326,
394,
4471,
358,
506,
444,
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,
444,
13621,
12,
2867,
394,
13621,
13,
2713,
288,
203,
3639,
1731,
1578,
1754,
273,
4471,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
272,
2233,
12,
3276,
16,
394,
13621,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-07
*/
// File: contracts/CryptoUncle12.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
}
// File: contracts/interfaces/ILayerZeroEndpoint.sol
pragma solidity >=0.5.0;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication) external view returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
}
// File: contracts/interfaces/ILayerZeroReceiver.sol
pragma solidity >=0.5.0;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_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");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/NonblockingReceiver.sol
pragma solidity ^0.8.6;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract");
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload));
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public {
// only internal transaction
require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge.");
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal;
function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal {
endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam);
}
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce];
require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message");
require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner {
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
// File: contracts/GhostlyGhosts.sol
pragma solidity ^0.8.7;
// #K#EL# .
// j,#.#W#E#### #
// #W#t###W######## fD
// .################K###
// ###################t####
// :#########################
// #############################,
// #G#############################
// ####G###############Df#######D
// ############################E##L
// ################Wf G####,###,
// i###K###.####E ##:## L##
// ##########, ## #G: W
// j######### .: #
// #########
// L########; #
// ########, W
// ########
// ######## f
// ######K Kj W. #
// ###### ##, # .#, #E
// ##### E G###W;#K## #DD
// ##### ;LW#t E#L# #G #;
// K# # ## # t i. #f
// # # # ##
// Wt if K t # # #
// Ki # # K: f##L:##G#
// # :j: tKjt. #
// W#tjG ####### .W
// W# ####Gi### WE
// # ## # D# #
// Dt ##:f :#D#
// # .### ## ###
// #: f##D E###L##
// , D###E#######
// E #tD###########
// # i############,
// ## L##########
// f####D L#######
// :E###########Wf ;###:
// L##########################
// i################# ###########D
// i###E ###############W#############
// #################################Gt###
// ########################################W
// W########################################W;.
// K####################LW######################
// ##############################################
// ###############################################
// .###K ###########################################t.
// ##############L####################j########jttttttttD#
// ###################################,########ttttttttttt
// ############################################ttttttttttE
// ############################################ttttttttttE
// t###########################################ttttttttttG
// ##########################:#################ttttttttttW
// #####:#################### ################ttttttttttD
// ##########################################Gfttttttttt#
// j################j#####################j tjttttttLKj
// ##################E##################W WtttED
// ##################################### tK #tK
// ############ ######################: ## :tW.E#j
// #############t#####################E WEt# G
// #############D###########, #######E E#; f: .
// #############E###################; :#K # tWj W
// #############E#################: f #,#L i
// ####G########f################# ,t ##; ,K##i :
// #####W#######;################W E####i ,E
// ############# ################K ####### L###
// ############# ######i :#######W #################.
// ############# ##: ,W########## .: W#################K
// ############ D############### #########################
// #########;:##############################################
// K#######K################################################
// i################# ##################;#####;.######## ###
// ####################################:###############.###
// ####################################################:###
// W#####################; ############################G###
// .###i,##############::#################################K
// #################:i###################################;
// E##############.G############t########################
// ############ W############# ########################i
// ;#########,############################## ##########
// #################K#################################
// K############### ################################
contract CryptoUncle12 is Ownable, ERC721, NonblockingReceiver {
address public _owner;
string private baseURI;
uint256 nextTokenId = 0;
uint256 MAX_MINT_ETHEREUM = 5000;
uint256 PRICE = 0.002 ether;
uint gasForDestinationLzReceive = 350000;
constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("CryptoUncle12 NFT", "CryptoUncle12") {
_owner = msg.sender;
endpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
baseURI = baseURI_;
}
// mint function
function mint(uint8 numTokens) external payable {
require((PRICE * numTokens) <= msg.value, "Not enough amount sent.");
require(nextTokenId + numTokens <= MAX_MINT_ETHEREUM, "CryptoUncle12: Mint exceeds supply");
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(msg.sender, ++nextTokenId);
}
}
// This function transfers the nft from your address on the
// source chain to the same address on the destination chain
function traverseChains(uint16 _chainId, uint tokenId) public payable {
require(msg.sender == ownerOf(tokenId), "You must own the token to traverse");
require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel");
// burn NFT, eliminating it from circulation on src chain
_burn(tokenId);
// abi.encode() the payload with the values to send
bytes memory payload = abi.encode(msg.sender, tokenId);
// encode adapterParams to specify more gas for the destination
uint16 version = 1;
bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
// get the fees we need to pay to LayerZero + Relayer to cover message delivery
// you will be refunded for extra gas paid
(uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams);
require(msg.value >= messageFee, "CryptoUncle12: msg.value not enough to cover messageFee. Send gas for message fees");
endpoint.send{value: msg.value}(
_chainId, // destination chainId
trustedRemoteLookup[_chainId], // destination address of nft contract
payload, // abi.encoded()'ed bytes
payable(msg.sender), // refund address
address(0x0), // 'zroPaymentAddress' unused for this
adapterParams // txParameters
);
}
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
function donate() external payable {
// thank you
}
// This allows the devs to receive kind donations
function withdraw(uint amt) external onlyOwner {
(bool sent, ) = payable(_owner).call{value: amt}("");
require(sent, "CryptoUncle12: Failed to withdraw Ether");
}
// just in case this fixed variable limits us from future integrations
function setGasForDestinationLzReceive(uint newVal) external onlyOwner {
gasForDestinationLzReceive = newVal;
}
// ------------------
// Internal Functions
// ------------------
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
// decode
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
require(_srcChainId!=0,"_srcChainId");
require(_srcAddress.length!=0,"_srcAddress");
require(_nonce!=0,"_nonce");
// mint the tokens back into existence on destination chain
_safeMint(toAddr, tokenId);
}
function _baseURI() override internal view returns (string memory) {
return baseURI;
}
} | decode mint the tokens back into existence on destination chain | function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
require(_srcChainId!=0,"_srcChainId");
require(_srcAddress.length!=0,"_srcAddress");
require(_nonce!=0,"_nonce");
_safeMint(toAddr, tokenId);
}
| 10,653,587 | [
1,
3922,
312,
474,
326,
2430,
1473,
1368,
15782,
603,
2929,
2687,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
48,
94,
11323,
12,
11890,
2313,
389,
4816,
3893,
548,
16,
1731,
3778,
389,
4816,
1887,
16,
2254,
1105,
389,
12824,
16,
1731,
3778,
389,
7648,
13,
3849,
2713,
288,
203,
3639,
261,
2867,
358,
3178,
16,
2254,
1147,
548,
13,
273,
24126,
18,
3922,
24899,
7648,
16,
261,
2867,
16,
2254,
10019,
203,
3639,
2583,
24899,
4816,
3893,
548,
5,
33,
20,
10837,
67,
4816,
3893,
548,
8863,
203,
3639,
2583,
24899,
4816,
1887,
18,
2469,
5,
33,
20,
10837,
67,
4816,
1887,
8863,
203,
3639,
2583,
24899,
12824,
5,
33,
20,
10837,
67,
12824,
8863,
203,
203,
3639,
389,
4626,
49,
474,
12,
869,
3178,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: APACHE 2.0
pragma solidity >0.7.0 <0.9.0;
import "./IRoleManager.sol";
import "./IRoleManagerAdmin.sol";
import "./IDelegateAdmin.sol";
/**
* @title RoleManager - Open Block Enterprise Initiative component
* @author Block Star Logic - Taurai Ushewokunze
* @dev This is the 'standard' implementation of the IRoleManager.sol and IRoleManagerAdmin.sol interfaces.
*/
contract RoleManager is IRoleManager, IRoleManagerAdmin {
IDelegateAdmin delegateAdmin;
// roles
string [] roleLists;
string [] barredLists;
mapping(string=>uint256) roleListIndexByRoleList;
mapping(string=>uint256) barredListIndexByBarredList;
mapping(string=>bool) knownListStatusByList;
mapping(string=>string) knownListTypeByList;
// addresses - Roles
mapping(string=>mapping(address=>bool))addressKnownStatusByAddressByRoleList;
mapping(string=>mapping(address=>bool))addressBarredStatusByAddressByRoleList;
mapping(string=>address[]) roleListAddressesByRoleList;
mapping(string=>mapping(address=>uint256)) roleListAddressIndexByRoleList;
mapping(string=>address[]) barredListAddressesByBarredList;
mapping(string=>mapping(address=>uint256)) barredListAddressIndexByBarredList;
mapping(address=>string[]) roleListsByAddress;
mapping(address=>mapping(string=>uint256)) roleListIndexByRoleListByAddress;
mapping(address=>string[]) barredListsByAddress;
mapping(address=>mapping(string=>uint256)) barredListIndexByRoleListByAddress;
mapping(address=>mapping(string=>uint256)) roleListForAddressIndexByAddress;
constructor(address delegateAdminAddress) {
delegateAdmin = IDelegateAdmin(delegateAdminAddress);
}
function isAllowed(string memory _roleList) override external view returns (bool _isAllowed){
return addressKnownStatusByAddressByRoleList[_roleList][msg.sender];
}
function isBarred(string memory _barredList) override external view returns(bool _isBarred){
return addressBarredStatusByAddressByRoleList[_barredList][msg.sender];
}
function getLists() override external returns (string[] memory _roleLists, string[] memory _barredLists){
delegateAdmin.isAdministratorOnly(msg.sender);
return (roleLists, barredLists);
}
function getListsForAddress(address _address) override external returns (string [] memory _roleLists, string [] memory _barredLists){
delegateAdmin.isAdministratorOnly(msg.sender);
return (roleListsByAddress[_address], barredListsByAddress[_address]);
}
function addAddressToList( string memory _list, address _address) override external returns (bool _added){
delegateAdmin.isAdministratorOnly(msg.sender);
if(isEqual("BARRED",knownListTypeByList[_list] )){
barredListAddressesByBarredList[_list].push(_address);
uint256 index = barredListAddressesByBarredList[_list].length;
barredListAddressIndexByBarredList[_list][_address] = index;
barredListsByAddress[_address].push(_list);
index = barredListsByAddress[_address].length;
barredListIndexByRoleListByAddress[_address][_list] = index;
}
else {
roleListAddressesByRoleList[_list].push(_address);
uint256 index = roleListAddressesByRoleList[_list].length;
roleListAddressIndexByRoleList[_list][_address] = index;
roleListsByAddress[_address].push(_list);
index = roleListsByAddress[_address].length;
roleListIndexByRoleListByAddress[_address][_list] = index;
}
return true;
}
function removeAddressFromList( string memory _list, address _address) override external returns (bool _removed){
delegateAdmin.isAdministratorOnly(msg.sender);
if(isEqual("BARRED",knownListTypeByList[_list] )){
uint256 index = barredListAddressIndexByBarredList[_list][_address];
delete barredListAddressesByBarredList[_list][index];
delete barredListAddressIndexByBarredList[_list][_address];
index = barredListIndexByRoleListByAddress[_address][_list];
delete barredListsByAddress[_address][index];
delete barredListIndexByRoleListByAddress[_address][_list];
}
else {
uint256 index = roleListAddressIndexByRoleList[_list][_address];
delete roleListAddressesByRoleList[_list][index];
delete roleListAddressIndexByRoleList[_list][_address];
index = roleListIndexByRoleListByAddress[_address][_list];
delete roleListsByAddress[_address][index];
delete roleListIndexByRoleListByAddress[_address][_list];
}
return true;
}
function addList(string memory _list, bool _isBarredList) override external returns (bool _added){
delegateAdmin.isAdministratorOnly(msg.sender);
require(!knownListStatusByList[_list], "arl 00 - known role."); // make sure we don't know this list already
uint256 index;
if(_isBarredList){
barredLists.push(_list);
index = barredLists.length;
barredListIndexByBarredList[_list] = index;
knownListTypeByList[_list] = "BARRED";
}
else {
roleLists.push(_list);
index = roleLists.length;
roleListIndexByRoleList[_list] = index;
knownListTypeByList[_list] = "ROLE";
}
knownListStatusByList[_list] = true; // now we know this list
return true;
}
function deleteList(string memory _list) override external returns (bool _deleted){
delegateAdmin.isAdministratorOnly(msg.sender);
require(knownListStatusByList[_list], "drl 00 - unknown list.");
if(isEqual("BARRED",knownListTypeByList[_list] )){
require(barredListAddressesByBarredList[_list].length == 0, " dl 00 barred list not empty. ");
uint256 index = barredListIndexByBarredList[_list];
delete barredLists[index];
delete barredListIndexByBarredList[_list];
}
else {
require(roleListAddressesByRoleList[_list].length == 0, " dl 01 role list not empty. ");
uint256 index = barredListIndexByBarredList[_list];
delete roleLists[index];
delete barredListIndexByBarredList[_list];
}
delete knownListStatusByList[_list];
delete knownListTypeByList[_list];
return true;
}
function getListAddresses(string memory _list) override external returns (address [] memory _addresses){
delegateAdmin.isAdministratorOnly(msg.sender);
require(knownListStatusByList[_list], "gla 00 - unknown list.");
if(isEqual("BARRED",knownListTypeByList[_list] )){
return barredListAddressesByBarredList[_list];
}
else {
return roleListAddressesByRoleList[_list];
}
}
function addressToString(address _address) internal pure returns (string memory _stringAddress){
return string(abi.encodePacked(_address));
}
function concat(string memory a, string memory b) internal pure returns (string memory _concatenated) {
return string(abi.encodePacked(a, b));
}
function isEqual(string memory a, string memory b ) internal pure returns (bool _isEqual) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
} | SPDX-License-Identifier: APACHE 2.0 | pragma solidity >0.7.0 <0.9.0;
| 14,124,595 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
432,
4066,
5007,
576,
18,
20,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
683,
9454,
18035,
560,
405,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
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;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(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;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many 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 HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (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 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes 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;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING
| function LOG714(string memory p0, address p1, address p2, address p3) internal view { | 14,087,854 | [
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,
202,
915,
2018,
27,
3461,
12,
1080,
3778,
293,
20,
16,
1758,
293,
21,
16,
1758,
293,
22,
16,
1758,
293,
23,
13,
2713,
1476,
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
] |
pragma solidity ^0.8.6;
import "../openzeppelin-contracts-upgradeable-master/contracts/token/ERC20/IERC20Upgradeable.sol";
import "../openzeppelin-contracts-upgradeable-master/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../openzeppelin-contracts-upgradeable-master/contracts/access/OwnableUpgradeable.sol";
import "../openzeppelin-contracts-upgradeable-master/contracts/proxy/utils/Initializable.sol";
import "../openzeppelin-contracts-upgradeable-master/contracts/security/PausableUpgradeable.sol";
import "./interfaces/IPureFiFarming.sol";
abstract contract PureFiPaymentPlan is Initializable, OwnableUpgradeable, PausableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct Vesting{
uint8 paymentPlan; //payment plan ID
uint64 startDate; //payment plan initiation date. Can be 0 if PaymentPlan refers to exact unlock timestamps.
uint256 totalAmount; //total amount of tokens vested for a person
uint256 withdrawnAmount; //amount withdrawn by user
}
mapping (address => Vesting) internal vestedTokens;
IERC20Upgradeable public token;
uint256 public totalVestedAmount; // total amount of vested tokens under this contract control.
address public farmingContract;
uint8 public farmingContractPool;
event Withdrawal(address indexed who, uint256 amount);
event PaymentPlanAdded(uint256 index);
event TokensVested(address indexed beneficiary, uint8 paymentPlan, uint64 startDate, uint256 amount);
function initialize(
address _token
) public initializer {
__Ownable_init();
__Pausable_init_unchained();
require(_token != address(0),"incorrect token address");
token = IERC20Upgradeable(_token);
}
function pause() onlyOwner public {
super._pause();
}
function unpause() onlyOwner public {
super._unpause();
}
function setFarmingContract(address _farmingContract, uint8 _farmingContractPool) onlyOwner public {
farmingContract = _farmingContract;
farmingContractPool = _farmingContractPool;
}
function vestTokens(uint8 _paymentPlan, uint64 _startDate, uint256 _amount, address _beneficiary) public onlyOwner whenNotPaused{
require(vestedTokens[_beneficiary].totalAmount == 0, "This address already has vested tokens");
require(_isPaymentPlanExists(_paymentPlan), "Incorrect payment plan index");
require(_amount > 0, "Can't vest 0 tokens");
require(token.balanceOf(address(this)) >= totalVestedAmount + _amount, "Not enough tokens for this vesting plan");
vestedTokens[_beneficiary] = Vesting(_paymentPlan, _startDate, _amount, 0);
totalVestedAmount += _amount;
emit TokensVested(_beneficiary, _paymentPlan, _startDate, _amount);
}
function withdrawAvailableTokens() public whenNotPaused {
(, uint256 available) = withdrawableAmount(msg.sender);
_prepareWithdraw(available);
token.safeTransfer(msg.sender, available);
}
function withdrawAndStakeAvailableTokens() public whenNotPaused {
require(farmingContract != address(0),"Farming contract is not defined");
(, uint256 available) = withdrawableAmount(msg.sender);
_prepareWithdraw(available);
//stake on farming contract instead of withdrawal
token.safeApprove(farmingContract, available);
IPureFiFarming(farmingContract).depositTo(farmingContractPool, available, msg.sender);
}
function withdraw(uint256 _amount) public whenNotPaused {
_prepareWithdraw(_amount);
token.safeTransfer(msg.sender, _amount);
}
function withdrawAndStake(uint256 _amount) public whenNotPaused{
require(farmingContract != address(0),"Farming contract is not defined");
_prepareWithdraw(_amount);
//stake on farming contract instead of withdrawal
token.safeApprove(farmingContract, _amount);
IPureFiFarming(farmingContract).depositTo(farmingContractPool, _amount, msg.sender);
}
function _prepareWithdraw(uint256 _amount) private {
require(vestedTokens[msg.sender].totalAmount > 0,"No tokens vested for this address");
(, uint256 available) = withdrawableAmount(msg.sender);
require(_amount <= available, "Amount exeeded current withdrawable amount");
require(available > 0, "Nothing to withdraw");
vestedTokens[msg.sender].withdrawnAmount += _amount;
totalVestedAmount -= _amount;
emit Withdrawal(msg.sender, _amount);
}
/**
* @param _beneficiary - address of the user who has his/her tokens vested on the contract
* returns:
* 0. next payout date for the user (0 if tokens are fully paid out)
* 1. amount of tokens that user can withdraw as of now
*/
function withdrawableAmount(address _beneficiary) public virtual view returns (uint64, uint256);
/**
* @param _beneficiary - address of the user who has his/her tokens vested on the contract
* returns:
* 0. payment plan ID
* 1. vesting start date. no claims before start date allowed
* 2. next unlock date. the date user can claim more tokens
* 3. total amount of tokens vested
* 4. withdrawn tokens amount (already claimed tokens, essentially)
* 5. amount of tokens that user can withdraw as of now
*/
function vestingData(address _beneficiary) public view returns (uint8, uint64, uint64, uint256, uint256, uint256) {
(uint64 nextUnlockDate, uint256 available) = withdrawableAmount(_beneficiary);
return (vestedTokens[_beneficiary].paymentPlan, vestedTokens[_beneficiary].startDate, nextUnlockDate, vestedTokens[_beneficiary].totalAmount, vestedTokens[_beneficiary].withdrawnAmount, available);
}
function _isPaymentPlanExists(uint8 _id) internal virtual view returns (bool);
}
| total amount of vested tokens under this contract control.
| uint256 public totalVestedAmount; | 5,415,456 | [
1,
4963,
3844,
434,
331,
3149,
2430,
3613,
333,
6835,
3325,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
2078,
58,
3149,
6275,
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
] |
./partial_match/80001/0x68e42D299Da641F2568e1AaCC640C71619603DF0/sources/AlchemistTradingRegistrar.sol | ************************************************************************************** External ************************************************************************************** Public* @dev Place Trade @param _tradeZip32 - zipped format for data of type bytes32 (0 => tradeId, 1 => buyerOrderId, 2 => sellerOrderId, 3 => ticker, 4 => token, 5 => UUID_BUYER, 6 => UUID_SELLER) @param _tradeZipUint256 - zipped format for data of type uint256 (0 => _price, 1 => _size, 2 => _buyCommission, 3 => sellCommission) @param _acknowledgedAt - timestamp of trade/ hasValidPrice(_tradeZipUint256[0]) update ERC20 balances save reverse indexes for buyer for seller update balances emit events | function placeTrade(
bytes32[] memory _tradeZip32,
uint256[] memory _tradeZipUint256,
uint256 _acknowledgedAt
)
public
isValidTradeID(_tradeZip32[0])
hasValidSize(_tradeZipUint256[1])
{
require(hasRole(TRADE_OPERATOR_ROLE, _msgSender()), "AlchemistTradingRegistrar: Operator Not allowed");
trades[_tradeZip32[0]] = TradeData(
_tradeZip32[5],
_tradeZip32[1],
_tradeZipUint256[0],
_tradeZipUint256[2],
_tradeZip32[4],
_tradeZip32[6],
_tradeZip32[2],
_tradeZipUint256[1],
_tradeZipUint256[3],
_tradeZip32[3],
_acknowledgedAt,
true
);
cTrades += 1;
_addOrders(_tradeZip32[1], _tradeZip32[0]);
_addUserOrder(_tradeZip32[5], _tradeZip32[1]);
_addUserTrade(_tradeZip32[5], _tradeZip32[0]);
_addOrders(_tradeZip32[2], _tradeZip32[0]);
_addUserOrder(_tradeZip32[6], _tradeZip32[2]);
_addUserTrade(_tradeZip32[6], _tradeZip32[0]);
_updateTokenBalance(
Side.BUYER,
_tradeZip32[4],
_tradeZip32[5],
_tradeZipUint256[1],
_tradeZipUint256[0],
_tradeZipUint256[2]
);
_updateTokenBalance(
Side.SELLER,
_tradeZip32[4],
_tradeZip32[6],
_tradeZipUint256[1],
_tradeZipUint256[0],
_tradeZipUint256[3]
);
emit Trade(
_tradeZip32[0],
_tradeZip32[5],
_tradeZip32[1],
_tradeZip32[6],
_tradeZip32[2],
_tradeZipUint256[1],
_tradeZipUint256[0],
_tradeZipUint256[2],
_tradeZipUint256[3],
_tradeZip32[3],
_tradeZip32[4]
);
}
| 8,808,430 | [
1,
6841,
225,
7224,
225,
13022,
2197,
323,
225,
389,
20077,
9141,
1578,
300,
3144,
1845,
740,
364,
501,
434,
618,
1731,
1578,
261,
20,
516,
18542,
548,
16,
404,
516,
27037,
21303,
16,
576,
516,
29804,
21303,
16,
890,
516,
14063,
16,
1059,
516,
1147,
16,
1381,
516,
5866,
67,
3000,
61,
654,
16,
1666,
516,
5866,
67,
1090,
4503,
654,
13,
225,
389,
20077,
9141,
5487,
5034,
300,
3144,
1845,
740,
364,
501,
434,
618,
2254,
5034,
261,
20,
516,
389,
8694,
16,
404,
516,
389,
1467,
16,
576,
516,
389,
70,
9835,
799,
3951,
16,
890,
516,
357,
80,
799,
3951,
13,
225,
389,
484,
10378,
2423,
861,
300,
2858,
434,
18542,
19,
711,
1556,
5147,
24899,
20077,
9141,
5487,
5034,
63,
20,
5717,
1089,
4232,
39,
3462,
324,
26488,
1923,
4219,
5596,
364,
27037,
364,
29804,
1089,
324,
26488,
3626,
2641,
2,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [
1,
202,
915,
3166,
22583,
12,
203,
202,
202,
3890,
1578,
8526,
3778,
389,
20077,
9141,
1578,
16,
203,
202,
202,
11890,
5034,
8526,
3778,
389,
20077,
9141,
5487,
5034,
16,
203,
202,
202,
11890,
5034,
389,
484,
10378,
2423,
861,
203,
202,
13,
203,
202,
202,
482,
203,
202,
202,
26810,
22583,
734,
24899,
20077,
9141,
1578,
63,
20,
5717,
203,
202,
202,
5332,
1556,
1225,
24899,
20077,
9141,
5487,
5034,
63,
21,
5717,
203,
202,
95,
203,
202,
202,
6528,
12,
5332,
2996,
12,
20060,
1639,
67,
26110,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
315,
1067,
1036,
376,
1609,
7459,
30855,
30,
11097,
2288,
2935,
8863,
203,
202,
202,
313,
16601,
63,
67,
20077,
9141,
1578,
63,
20,
13563,
273,
2197,
323,
751,
12,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
25,
6487,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
21,
6487,
203,
1082,
202,
67,
20077,
9141,
5487,
5034,
63,
20,
6487,
203,
1082,
202,
67,
20077,
9141,
5487,
5034,
63,
22,
6487,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
24,
6487,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
26,
6487,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
22,
6487,
203,
1082,
202,
67,
20077,
9141,
5487,
5034,
63,
21,
6487,
203,
1082,
202,
67,
20077,
9141,
5487,
5034,
63,
23,
6487,
203,
1082,
202,
67,
20077,
9141,
1578,
63,
23,
6487,
203,
1082,
202,
67,
484,
10378,
2423,
861,
16,
203,
1082,
202,
3767,
203,
202,
202,
1769,
203,
203,
202,
202,
71,
1609,
2
] |
pragma solidity 0.5.8;
import "./Roles.sol";
contract InspectorRole {
using Roles for Roles.Role;
mapping(uint32 => Request) public requests;
// Latest Request ID for requests represented by contract
uint32 public requestId;
enum RequestState {
Requested, // 0
Approved, // 1
Denied, // 2
Viewed // 3
}
struct Request {
RequestState requestState; // Product State as represented in the enum above
address inspectorId; // Metamask-Ethereum address
uint32 certificateId; // Certificate that this Request is referencing
}
// Events for Requests
event Requested(uint32 certificateId, uint32 requestId);
event Approved(uint32 requestId);
event Denied(uint32 requestId);
event Viewed(uint32 requestId);
// Define 2 events, one for Adding, and other for Removing
event InspectorAdded(address indexed account);
event InspectorRemoved(address indexed account);
// Inheriting struct Role from 'Roles' library,
Roles.Role private inspectors;
// In the constructor make the address that deploys this contract the 1st inspector
constructor() public {
requestId = 1;
_addInspector(msg.sender);
}
// Define a modifier that checks to see if msg.sender has the appropriate role
modifier onlyInspector() {
require(isInspector(msg.sender));
_;
}
// Define a function 'isInspector' to check this role
function isInspector(address account) public view returns (bool) {
return inspectors.has(account);
}
// Define a function 'addInspector' that adds this role
function addInspector(address account) public onlyInspector {
_addInspector(account);
}
// Define a function 'renounceInspector' to renounce this role
function renounceInspector() public {
_removeInspector(msg.sender);
}
// Define an internal function '_addInspector' to add this role, called by 'addInspector'
function _addInspector(address account) internal {
inspectors.add(account);
emit InspectorAdded(account);
}
// Define an internal function '_removeInspector' to remove this role, called by 'renounceInspector'
function _removeInspector(address account) internal {
inspectors.remove(account);
emit InspectorRemoved(account);
}
// Modifier to assert request state
modifier requested(uint32 _requestId) {
require(requests[_requestId].requestState == RequestState.Requested, "Access has not been requested");
_;
}
// Modifier to assert request state
modifier approved(uint32 _requestId) {
require(requests[_requestId].requestState == RequestState.Approved, "Access has not been approved");
_;
}
// Only the Inspector can view the certificate
modifier onlyRequestor(uint32 _requestId) {
require(msg.sender == requests[_requestId].inspectorId,
"Only the address that requested access can view the certificate");
_;
}
// An inspector has request access to view a Recipient's certification
function requestAccess(uint32 _certificateId) public {
requests[requestId].requestState = RequestState.Requested;
requests[requestId].inspectorId = msg.sender;
requests[requestId].certificateId = _certificateId;
emit Requested(_certificateId, requestId);
requestId++;
}
// An inspector has viewed a certificate that has had access approved
function viewCertificate(uint32 _requestId) public approved(_requestId) onlyRequestor(_requestId) {
requests[_requestId].requestState = RequestState.Viewed;
emit Viewed(_requestId);
}
}
| Certificate that this Request is referencing
| uint32 certificateId; | 1,074,548 | [
1,
4719,
716,
333,
1567,
353,
24509,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1578,
4944,
548,
31,
3639,
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/0x563D8676Fc2575CA42356F532dcCa482B5A92260/sources/_solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol | * @inheritdoc IERC1155Enumerable/ | function tokensByAccount(
address account
) public view virtual returns (uint256[] memory) {
return _tokensByAccount(account);
}
| 9,453,054 | [
1,
36,
10093,
467,
654,
39,
2499,
2539,
3572,
25121,
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,
2430,
858,
3032,
12,
203,
3639,
1758,
2236,
203,
565,
262,
1071,
1476,
5024,
1135,
261,
11890,
5034,
8526,
3778,
13,
288,
203,
3639,
327,
389,
7860,
858,
3032,
12,
4631,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0x94D179B042c24850988901aDc837a78B2e426428/sources/project_/contracts/utils/GoodDollarMintBurnWrapper.sol | * @notice pause one of the functions of the wrapper (see pause roles), only dev/guardian roles can call this @param role which function to pause/ | function pause(bytes32 role)
external
onlyRoles([GUARDIAN_ROLE, DEFAULT_ADMIN_ROLE])
{
_pause(role);
}
| 3,497,039 | [
1,
19476,
1245,
434,
326,
4186,
434,
326,
4053,
261,
5946,
11722,
4900,
3631,
1338,
4461,
19,
24594,
2779,
4900,
848,
745,
333,
225,
2478,
1492,
445,
358,
11722,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
11722,
12,
3890,
1578,
2478,
13,
203,
202,
202,
9375,
203,
202,
202,
3700,
6898,
3816,
30673,
985,
2565,
1258,
67,
16256,
16,
3331,
67,
15468,
67,
16256,
5717,
203,
202,
95,
203,
202,
202,
67,
19476,
12,
4615,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
pair = pairmanager.pairFor(tokenA, tokenB, _salt);
}
function createPair(address _tokenA, address _tokenB, bytes32 salt) external {
require(_tokenA != _tokenB ||
keccak256(abi.encodePacked(IERC20(_tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
"pair same token invalid");
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//create pair
(address token0, address token1, uint16 token0_id, uint16 token1_id) = _tokenA < _tokenB ? (_tokenA, _tokenB, tokenAID, tokenBID) : (_tokenB, _tokenA, tokenBID, tokenAID);
address pair = pairmanager.createPair(token0, token1, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
token0_id,
token1_id,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20, bytes32 salt) external {
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
erc20ID,
validatePairTokenAddress(pair),
pair);
}
function registerCreatePair(uint16 _tokenA, uint16 _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
(uint16 token0, uint16 token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
Operations.CreatePair memory op = Operations.CreatePair({
accountId: 0, //unknown at this point
tokenA: token0,
tokenB: token1,
tokenPair: _tokenPair,
pair: _pair
});
// pubData
bytes memory pubData = Operations.writeCreatePairPubdata(op);
addPriorityRequest(Operations.OpType.CreatePair, pubData);
emit OnchainCreatePair(token0, token1, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeNoticePeriodStarted() external override {}
/// @notice Notification that upgrade preparation status is activated
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradePreparationStarted() external override {
upgradePreparationActive = true;
upgradePreparationActivationTime = block.timestamp;
}
/// @notice Notification that upgrade canceled
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeCanceled() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeFinishes() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external view override returns (bool) {
return !exodusMode;
}
/// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// @dev _governanceAddress The address of Governance contract
/// @dev _verifierAddress The address of Verifier contract
/// @dev _pairManagerAddress the address of UniswapV2Factory contract
/// @dev _zkSyncCommitBlockAddress the address of ZkSyncCommitBlockAddress contract
/// @dev _genesisStateHash Genesis blocks (first block) state tree root hash
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress,
address _zkSyncCommitBlockAddress,
bytes32 _genesisStateHash
) = abi.decode(initializationParameters, (address, address, address, address, address, bytes32));
governance = Governance(_governanceAddress);
verifier = Verifier(_verifierAddress);
verifier_exit = VerifierExit(_verifierExitAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
// We need initial state hash because it is used in the commitment of the next block
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION);
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData);
priorityRequests[nextPriorityRequestId] = PriorityOperation({
hashedPubData: hashedPubData,
expirationBlock: expirationBlock,
opType: _opType
});
emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock));
totalOpenPriorityRequests++;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external nonReentrant {
require(totalBlocksCommitted == totalBlocksProven, "wq1"); // All the blocks must be proven
require(totalBlocksCommitted == totalBlocksExecuted, "w12"); // All the blocks must be executed
if (upgradeParameters.length != 0) {
StoredBlockInfo memory lastBlockInfo;
(lastBlockInfo) = abi.decode(upgradeParameters, (StoredBlockInfo));
storedBlockHashes[totalBlocksExecuted] = hashStoredBlockInfo(lastBlockInfo);
}
zkSyncCommitBlockAddress = address(0xcb4c185cC1bC048742D3b6AB760Efd2D3592c58f);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "L"); // exodus mode activated
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess == _depositsPubdata.length, "A");
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
function depositETH() external payable {
require(msg.value > 0, "1");
requireActive();
require(tokenIds[msg.sender] == 0, "da");
registerDeposit(0, SafeCast.toUint128(msg.value), msg.sender);
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
function depositERC20(IERC20 _token, uint104 _amount) external nonReentrant {
requireActive();
require(tokenIds[msg.sender] == 0, "db");
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
require(_token.balanceOf(address(this)) + _amount <= MAX_ERC20_TOKEN_BALANCE, "bgt");
} else {
// lpToken
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
// lpToken
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); //
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C1");
registerDeposit(lpTokenId, deposit_amount, msg.sender);
} else {
// token
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C2");
registerDeposit(tokenId, deposit_amount, msg.sender);
}
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _token Address of token, zero address is used for ETH
function getPendingBalance(address _address, address _token) public view returns (uint128) {
uint16 tokenId = 0;
if (_token != address(0)) {
tokenId = governance.validateTokenAddress(_token);
}
return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw;
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _tokenId token id, 0 is used for ETH
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function requestFullExit(uint32 _accountId, address _token) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
uint16 tokenId;
uint16 lpTokenId = tokenIds[_token];
if (_token == address(0)) {
tokenId = 0;
} else if (lpTokenId == 0) {
// This means it is not a pair address
// 非lpToken
tokenId = governance.validateTokenAddress(_token);
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
} else {
// lpToken
tokenId = lpTokenId;
}
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0, // unknown at this point
pairAccountId: 0
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE;
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function activateExodusMode() public returns (bool) {
bool trigger =
block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op =
Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount,
pairAccountId: 0
});
bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
fallback() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// 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;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
require(lockSlotOldValue == 0, "1B");
}
/**
* @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() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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, "14");
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, "v");
}
/**
* @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, "15");
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, "x");
}
/**
* @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, "y");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "12");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "aa");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 c = a * b;
require(c / a == b, "13");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "ad");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
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, "16");
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, "17");
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, "18");
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, "19");
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, "1a");
return uint8(value);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
mstore(_bytes, sub(bytesLen, 32))
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title zkSync storage contract
/// @author Matter Labs
contract Storage {
/// @dev Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool internal upgradePreparationActive;
/// @dev Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradePreparationActivationTime;
/// @dev Verifier contract. Used to verify block proof
Verifier public verifier;
/// @dev Verifier contract. Used to verify exit proof
VerifierExit public verifier_exit;
/// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance public governance;
// NEW ADD
UniswapV2Factory internal pairmanager;
uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance
struct PendingBalance {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => PendingBalance) public pendingBalances;
/// @notice Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis)
uint32 public totalBlocksExecuted;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public performedExodus;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @Rollup block stored data
/// @member blockNumber Rollup block number
/// @member priorityOperations Number of priority operations processed
/// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify
/// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant
/// @member stateHash Root hash of the rollup state
/// @member commitment Verified input for the zkSync circuit
struct StoredBlockInfo {
uint32 blockNumber;
uint64 priorityOperations;
bytes32 pendingOnchainOperationsHash;
uint256 timestamp;
bytes32 stateHash;
bytes32 commitment;
}
/// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) public pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
/// @dev Stored hashed StoredBlockInfo for some block number
mapping(uint32 => bytes32) public storedBlockHashes;
/// @notice Total blocks proven.
uint32 public totalBlocksProven;
/// @notice Priority Operation container
/// @member hashedPubData Hashed priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
/// @member opType Priority operation type
struct PriorityOperation {
bytes20 hashedPubData;
uint64 expirationBlock;
Operations.OpType opType;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
// requestId -> PriorityOperation
mapping(uint64 => PriorityOperation) public priorityRequests;
// NEW ADD
address public zkSyncCommitBlockAddress;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
/// @author Stars Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev Bytes in one chunk
uint8 constant CHUNK_BYTES = 9;
/// @dev zkSync address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 511;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
/// @dev Max ERC20 token balance that is possible to deposit, suppose ((2**126) - 1)
uint128 internal constant MAX_ERC20_TOKEN_BALANCE = (2**126) - 1;
/// @dev Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 constant WITHDRAW_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
// NEW ADD
uint256 constant CREATE_PAIR_BYTES = 4 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 14 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 constant MASS_FULL_EXIT_PERIOD = 9 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 constant UPGRADE_NOTICE_PERIOD = 0 days;
/// @dev Timestamp - seconds since unix epoch
uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 168 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 constant INPUT_MASK = (~uint256(0) >> 3);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
/// @author Stars Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) {
require(_new_length <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _new_length, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
/// @author Matter Labs
/// @author Stars Labs
library Operations {
/// @notice zkSync circuit operation type
enum OpType {
Noop, //0
Deposit,
TransferToNew,
Withdraw,
Transfer,
FullExit, //5
ChangePubKey,
MiningMaintenance,
ClaimBonus,
CreatePair,
AddLiquidity,//10
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant OP_TYPE_BYTES = 1;
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @dev Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
// NEW ADD pairAccountId
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner, // owner
bytes4(0) // pairAccountId
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
// NEW ADD pairAccountId
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
// NEW ADD pairAccountId
uint32(0) // pairAccountId -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// Withdraw pubdata
struct Withdraw {
//uint8 opType; -- present in pubdata, ignored at serialization
// NEW ADD
uint32 accountId;
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
// NEW ADD
uint32 pairAccountId;
}
function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
// CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES;
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
// NEW ADD
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint16 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// CreatePair pubdata
// NEW ADD
struct CreatePair {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
// NEW ADD
uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
// NEW ADD
function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed)
{
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
// NEW ADD
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
OpType.CreatePair,
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
contract PairTokenManager {
/// @dev Max amount of pair tokens registered in the network.
/// This is computed by: 2048 - 512 = 1536
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 1536;
uint16 constant PAIR_TOKEN_START_ID = 512;
/// @dev Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @dev List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @dev List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @dev Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
// tokenId -> token
tokenAddresses[newPairTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @dev Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId < (PAIR_TOKEN_START_ID + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
require(tokenId >= PAIR_TOKEN_START_ID, "pms5");
return tokenId;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
function symbol() external pure returns (string memory);
/**
* @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.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireGovernor(msg.sender);
require(_token != address(0), "1e0");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
// tokenId -> token
tokenAddresses[newTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkVerifier, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyAggregatedBlockProof(
uint256[] memory _recursiveInput,
uint256[] memory _proof,
uint8[] memory _vkIndexes,
uint256[] memory _individual_vks_inputs,
uint256[16] memory _subproofs_limbs
) external view returns (bool) {
for (uint256 i = 0; i < _individual_vks_inputs.length; ++i) {
uint256 commitment = _individual_vks_inputs[i];
_individual_vks_inputs[i] = commitment & INPUT_MASK;
}
VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length));
return
verify_serialized_proof_with_recursion(
_recursiveInput,
_proof,
VK_TREE_ROOT,
VK_MAX_INDEX,
_vkIndexes,
_individual_vks_inputs,
_subproofs_limbs,
vk
);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkVerifierOld, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment =
sha256(abi.encodePacked(uint256(_rootHash) , _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _token_data,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory commit_data = concatBytes(_account_data, _token_data);
bytes32 commitment = sha256(commit_data);
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExitLp();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
}
pragma solidity ^0.7.0;
import './UniswapV2Pair.sol';
import "../IERC20.sol";
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract UniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() {}
function initialize(bytes calldata data) external {}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp2');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
address(this),
salt,
keccak256(bytecode)
))));
}
function createPair(address tokenA, address tokenB, bytes32 _salt) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB ||
keccak256(abi.encodePacked(IERC20(tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
UniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
UniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./PlonkCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifier is VerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x108678a23c44e8c0b590d3204fa7b710b4e74e590722c4d1f42cd1e6744bf4d3;
uint8 constant VK_MAX_INDEX = 3;
function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) {
if (_proofs == uint32(1)) { return getVkAggregated1(); }
else if (_proofs == uint32(4)) { return getVkAggregated4(); }
else if (_proofs == uint32(8)) { return getVkAggregated8(); }
else if (_proofs == uint32(18)) { return getVkAggregated18(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated4() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 8388608;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6,
0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089,
0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d,
0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b,
0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a,
0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43,
0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec,
0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb,
0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4,
0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df,
0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c,
0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a,
0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352,
0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated8() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f,
0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8,
0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2,
0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956,
0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9,
0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f,
0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64,
0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f,
0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015,
0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d,
0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2,
0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200,
0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a,
0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated18() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 33554432;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0d94d63997367c97a8ed16c17adaae39262b9af83acb9e003f94c217303dd160);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x0eab7c0217fbc357eb9e2622da6e5df9a99e5fa8dbaaf6b45a7136bbc49704c0,
0x00199f1c9e2ef5efbec5e3792cb6db0d6211e2da57e2e5a7cf91fb4037bd0013
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x020c5ecdbb37b9f99b131cdfd0fec8c5565985599093db03d85a9bcd75a8a186,
0x0be3b767834382739f1309adedb540ce5261b7038c168d32619a6e6333974b1b
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x092fc8636803f28250ac33b8ea688b37cf0718f83c82a1ce7bca70e7c8643b93,
0x10c907fcb34fb6e9d4e334428e8226ba84e5977a7dc1ada2509cc6cf445123ca
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1f66b77eaae034cf3646e0c32418a1dfecb3bf090cc271aad0d64ba327758b29,
0x2b8766fbe83c45b39e274998a000cf59e7332800025e7af711368c6b7ea11cd9
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x017336a15f6e61def3ec02f139a0972c4272e126ac40d49ed10d447db6857643,
0x22cc7cb62310a031acd86dd1a9ea18ee55e1b6a4fbf1c2d64ca9a7cc6458ed7a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x057992ff5d056557b795ab7e6964fab546fdcd8b5c1d3718e4f619e1091ef9a0,
0x026916de04486781c504fb054e0b3755dd4836b610973e0ca092b35810ed3698
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x252a53377145970214c9af5cd95c5fdd72e4d890b96d5ab31ef7736b2280aaa3,
0x2a1ccbea423d1a58325c4d0e5aa01a6a2a7c7fbaa61fb8f3669f720dfb4dfd4d
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x17da1e8102c91916c778e89d737bdc8a14f4dfcf14fc89896f921dfc81e98556,
0x1b9571239471b65bc5d4bcc3b1b3831bcc6986ad4d1417292dc3067ae632b796
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x242b5b8848746eb790629cf0853e256249d83cad8e189d474ed3a5c56b5a92be,
0x2ca4e4882f0d7408ba134458945a2dd7cbced64e735fd42c9204eaf8608c58cc
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x281ccb20cea7001ae0d3ef5deedc46db687f1493cd77631dc2c16275b96f677a,
0x24bede6b53ee4762939dbabb5947023d3ab31b00a1d14bcb6a5da69d7ce0d67e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x1e72df4c2223fb15e72862350f51994b7f381a829a00b21535b04e8c342c15e7,
0x22b7bb45c2e3b957952824beee1145bfcb5d2c575636266ad44032c1ae24e1ea
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x0059ea736670b355b3b6479db53d9b19727aa128514dee7d6c6788e80233452f,
0x24718998fb0ff667c66457f6558ff028352b2d55cb86a07a0c11fc3c2753df38
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x0bee5ac3770c7603b2ccbc9e10a0ceafa231e77dde3fd6b9d514958ae7c200e8,
0x11339336bbdafda32635c143b7bd0c4cdb7b7948489d75240c89ca2a440ef39c
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld {
function getVkExit() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1775efa56023e26c6298b2775481c0add1d64120dd242eb7e66cfebe43a8689d,
0x0adc370e09dc4bfcd73bf48ac1735363d2801dc50b903b950c2259cfec908422
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x1af5b8c0863df35aa93be8f75480bb8c4ad103993c05408856365dce2151cf72,
0x2aa95351d73b68ca33f9a8451cafeca8d9b66b9a5253b1196714d2d55f18c74e
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1a83514953af1d12f597ae8e159a69efdb4a19bc448f9bc3c100a5d27ab66467,
0x2e739d3240d665dba7ba612ca8548a2817ef3b26a5e31afd66121179860fb367
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x10fdde5088f9df8c2af09166c3e1d2aaf5bedaaf14095a81680285a7ea9a3207,
0x03cb4d015d2c8ab50e6e15c59aaeb0cc6f9dba3731c06513df9c3f77dcc7a75b
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x2e5f67efb618542c634c0cfef443d3ae7d57621fcc487e643d9174b1982ca106,
0x2a7761839026029cb215da80cfe536a4d6f7e993a749e21a0c430a455a6f6477
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x14ee91feb802eea1204e0b4faf96bd000d03e03a253e68f5e44e46880327eaa3,
0x1adfa909fe1008687d3867162b18aa895eed7a5dd10eeeee8d93876f9972f794
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x218b439287375a3f3cc2cad85805b47be7a0c5e8dd43c8c42305f7cb3d153fea,
0x1f94bb4131aee078b207615def18b0f2e94a966ce230fb1837df244657b06b60
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x0dc7db7aea2ef0f5d3b072faeaaee44bb1a79715e977bf87321d210140f4b443,
0x2ceb58346301f008a7553fe2851524e613d8060f309def3239494c2ac4722b99
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1d4ee99264d715b08b84286e6c979c47446b2cab86f6bb06d937e1d64814a322,
0x2cf40326362bbc1531e3d32e844e2986484ad74fac2b7e5c10bc5375f39dd271
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x20ffb570ec9e40ec87c2df09ec417e301d44db21323e2440134844a0d6aa18cf,
0x2d45d5f1e6fcfed9239d8f464c02a815498261b9a3edec9f4e1cd2058425aa96
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x28f43e5e320de920d29b0eabd68b6b93ea8beb12f35310b96b63ece18b8d99d3,
0x206324d60731845d125e4869c90ae15be2d160886b91bf3c316ac59af0688b6e
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkExitLp() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x15a418864253e30d92e0af8f44c45679ab52bb172c65bd1ca649bd352c55eb2f,
0x25d9ce8e852566a5a460653a634708f768f61da8bd3b986ac022cff0067011c2
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x2a7b4444d1b2eaad9dbd93c6bbae7d133fbaf0f71e3e769d35a379e63be37a97,
0x1420d2079a52ce83ee6b498e8a3fa498ec3bd48b92894a17996dfd23fbab90e3
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x17ad336a0139401277e75660ef40b0f07347f6d72d6b143e485953fc896cce9a,
0x227fcdd90c6dfc955c796e544e8bf0ea243e2ce0022e563716a5153260ceea6d
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x2c115c4700fc64f25ac77ba471b1dd5128c439163555331e1078cd6ee5627ba0,
0x2066980b107e6f2fa8160aaa88cb90113d2fd94ad62cd3366848c6746afa6acf
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x256677a67eca0e07a491e652e8e529e9d61e8833a7f90e8c2f1cdb6872260115,
0x0d1f62a5228c35e872a1146944c383d2d2d16dca4e8875bbf70f4d4b8834b6f5
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x1b041e5c782b57147cdfc17aad8b5881ebf895b75cf9d97f45c592f4dcfe640d,
0x01fbc948fd4701103a10bd5fee07fae81481e4f9ca90e36bd12c2ecfb1768b71
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x24d84ac5c820acc4ee6b6062092adc108c640a5750d837b28e5044bf992b45ef,
0x1faacb531160847bb4712202ee2b15a102084c24a2a8da1b687df5de8b2b6dd1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x28b25ca568d481180c47ff7f7beb6fa426c033c201a140c71cc5bbd090a69474,
0x0bc1b33a8d4a834cdb5b40ba275e2b33089120239abf4f9ffce983d1cfc9a85a
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x11012d815b96d6f9c95a50dd658f45d443472ee0432045f980f2c2745e4c3847,
0x235e2e22940391f97fcedda2690f3265ec813a964f95475f282c0f16602c1fb4
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2d7bb392ede616e3832f054a5ef35562522585563f1e978cbd3732069bcf4a24,
0x2b97bf5dd09f2765a35f1eeb2936767c20095d03666c1a5948544a74289a51df
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x0c3808600cf3d62ade4d2bb6cb856117f717ccd2a5cd2d549cdae1ad86bbb12b,
0x20827819d88e1dac7cd8f7cd1abce9eff8e9c936dbd305c364f0337298daa5b9
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod - 2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] X;
uint256[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return
G2Point(
[
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed
],
[
0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2) internal view {
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view {
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) {
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s) internal view {
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(
G1Point memory p,
Fr memory s,
G1Point memory dest
) internal view {
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length);
uint256 elements = p1.length;
uint256 inputSize = elements * 6;
uint256[] memory input = new uint256[](inputSize);
for (uint256 i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
contract Plonk4VerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK =
0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk)
internal
view
returns (bool valid, PairingsBn254.G1Point[2] memory part)
{
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(
recursive_proof_part[0],
PairingsBn254.P2(),
recursive_proof_part[1],
vk.g2_x
);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) =
reconstruct_recursive_public_input(
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] +
(subproofs_aggregated[1] << LIMB_WIDTH) +
(subproofs_aggregated[2] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[3] << (3 * LIMB_WIDTH)),
subproofs_aggregated[4] +
(subproofs_aggregated[5] << LIMB_WIDTH) +
(subproofs_aggregated[6] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[7] << (3 * LIMB_WIDTH))
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] +
(subproofs_aggregated[9] << LIMB_WIDTH) +
(subproofs_aggregated[10] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[11] << (3 * LIMB_WIDTH)),
subproofs_aggregated[12] +
(subproofs_aggregated[13] << LIMB_WIDTH) +
(subproofs_aggregated[14] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[15] << (3 * LIMB_WIDTH))
);
return (recursive_input, reconstructed_g1s);
}
}
contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (Proof memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid =
verify_recursive(
proof,
vk,
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
return valid;
}
}
contract Plonk4VerifierWithAccessToDNextOld {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH_OLD = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1;
struct VerificationKeyOld {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct ProofOld {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierStateOld {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain_old(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain_old(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) {
PartialVerifierStateOld memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld {
uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33;
function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (ProofOld memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
}
pragma solidity ^0.7.0;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
contract UniswapV2Pair is UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint256 amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint256 amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity ^0.7.0;
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'EdgeSwap V1';
string public constant symbol = 'Edge-V1';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity ^0.7.0;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity ^0.7.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity ^0.7.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
} | * @dev Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./ | interface IERC20 {
function symbol() external pure returns (string memory);
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);
}
| 72,361 | [
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
9637,
486,
2341,
326,
3129,
4186,
31,
358,
2006,
2182,
2621,
288,
654,
39,
3462,
40,
6372,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
467,
654,
39,
3462,
288,
203,
203,
565,
445,
3273,
1435,
3903,
16618,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/math/SafeMath.sol";
import "./ERC20.sol";
contract BuyAndSell1 {
using SafeMath for uint256; //
//1000000000000000000
mapping(address => uint256) public _buyPriceByEth;
mapping(address => uint256) public _balanceByEth;
mapping(address => mapping(address=>uint256)) public _buyPriceByToken;
// mapping(address => uint256) public _balanceByEth;
address private owner;
modifier isOwner{
require(msg.sender == owner,"Only owner can do this");
_;
}
constructor(){
owner = msg.sender;
}
function setBuyPriceEth(address _tokenAddress, uint256 buyPrice) public isOwner {
_buyPriceByEth[_tokenAddress] = buyPrice;
ERC20 token = ERC20(_tokenAddress);
_balanceByEth[_tokenAddress] = token.balanceOf(address(this));
}
function setBuyPriceToken(address _tokenAddress,address _usdtAdress, uint256 buyPrice) public isOwner {
_buyPriceByToken[_tokenAddress][_usdtAdress] = buyPrice;
}
function buyByEth(address _tokenAddress) public payable returns (bool){
ERC20 token = ERC20(_tokenAddress);
require(_buyPriceByEth[_tokenAddress]!=0,"Don't support to buy this token");
uint256 value = msg.value;
uint256 _amount = value.div(_buyPriceByEth[_tokenAddress],"Buy price cant be Zero");
require(_amount > 0,"Too little ether to buy token");
require(_balanceByEth[_tokenAddress] >= _amount, "Not enough Token to buy");
bool result = token.transfer(msg.sender,_amount);
return result;
}
function buyByToken(address _tokenAddress,address _usdtAdress,uint256 _amount,address _spender) public payable returns (bool){
require(_tokenAddress!= address(0),"Token address != 0x0");
require(_usdtAdress!= address(0),"USDT address != 0x0");
require(_spender!= address(0),"Spender address != 0x0");
ERC20 usdt = ERC20(_usdtAdress);
// Token to send for USDT
ERC20 token = ERC20(_tokenAddress);
usdt.transferFrom(_spender, address(this), _amount);
_amount= _amount.mul(2);
// Send amount tokens to msg.sender
token.transfer(msg.sender, _amount);
return true;
}
function withDrawToken(address _tokenAddress) isOwner public returns(bool){
ERC20 token = ERC20(_tokenAddress);
uint256 _amount = token.balanceOf(address(this));
bool result = token.transfer(owner,_amount);
return result;
}
function withDrawEth(uint256 _amount) isOwner public{
uint256 amountOfContract = address(this).balance;
require(_amount<=amountOfContract,"Dont have enough Eth to transfer");
payable(msg.sender).transfer(_amount);
}
} | Token to send for USDT Send amount tokens to msg.sender | function buyByToken(address _tokenAddress,address _usdtAdress,uint256 _amount,address _spender) public payable returns (bool){
require(_tokenAddress!= address(0),"Token address != 0x0");
require(_usdtAdress!= address(0),"USDT address != 0x0");
require(_spender!= address(0),"Spender address != 0x0");
ERC20 usdt = ERC20(_usdtAdress);
ERC20 token = ERC20(_tokenAddress);
usdt.transferFrom(_spender, address(this), _amount);
_amount= _amount.mul(2);
token.transfer(msg.sender, _amount);
return true;
}
| 5,407,650 | [
1,
1345,
358,
1366,
364,
11836,
9081,
2479,
3844,
2430,
358,
1234,
18,
15330,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
30143,
858,
1345,
12,
2867,
389,
2316,
1887,
16,
2867,
389,
407,
7510,
1871,
663,
16,
11890,
5034,
389,
8949,
16,
2867,
389,
87,
1302,
264,
13,
1071,
8843,
429,
1135,
261,
6430,
15329,
203,
3639,
2583,
24899,
2316,
1887,
5,
33,
1758,
12,
20,
3631,
6,
1345,
1758,
480,
374,
92,
20,
8863,
203,
3639,
2583,
24899,
407,
7510,
1871,
663,
5,
33,
1758,
12,
20,
3631,
6,
3378,
9081,
1758,
480,
374,
92,
20,
8863,
203,
3639,
2583,
24899,
87,
1302,
264,
5,
33,
1758,
12,
20,
3631,
6,
27223,
264,
1758,
480,
374,
92,
20,
8863,
203,
3639,
4232,
39,
3462,
584,
7510,
273,
4232,
39,
3462,
24899,
407,
7510,
1871,
663,
1769,
203,
203,
3639,
4232,
39,
3462,
1147,
273,
4232,
39,
3462,
24899,
2316,
1887,
1769,
203,
3639,
584,
7510,
18,
13866,
1265,
24899,
87,
1302,
264,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
389,
8949,
33,
389,
8949,
18,
16411,
12,
22,
1769,
203,
3639,
1147,
18,
13866,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/interfaces/IOptionToken.sol | * @title IOptionToken interface @author DeOrderBook @custom:license Copyright (c) DeOrderBook, 2023 — All Rights Reserved @dev Interface for managing option token contracts/ | interface IOptionToken {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function mintFor(address _account, uint256 _amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function updateSymbol(string memory _new_symbol) external;
function activeInit(uint256 _optionID, string memory _new_name, string memory _new_symbol) external;
pragma solidity 0.8.4;
}
| 8,402,303 | [
1,
45,
1895,
1345,
1560,
225,
1505,
2448,
9084,
632,
3662,
30,
12687,
25417,
261,
71,
13,
1505,
2448,
9084,
16,
26599,
23,
225,
163,
227,
247,
4826,
534,
10730,
16237,
225,
6682,
364,
30632,
1456,
1147,
20092,
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,
5831,
1665,
375,
1345,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
312,
474,
1290,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
18305,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
203,
565,
445,
18305,
1265,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
31,
203,
203,
565,
445,
1089,
5335,
12,
1080,
3778,
389,
2704,
67,
7175,
13,
3903,
31,
203,
203,
565,
445,
2695,
2570,
12,
11890,
5034,
389,
3482,
734,
16,
533,
3778,
389,
2704,
67,
529,
16,
533,
3778,
389,
2704,
67,
7175,
13,
3903,
31,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
24,
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,
-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;
/**
* @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 "./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/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC721Tradable.sol";
/**
* @title ARA NFTs
* Base contract to create and distribute rewards to the ARA community
*/
contract ARA is ERC721Tradable {
using Address for address;
using Counters for Counters.Counter;
// ============================== Variables ===================================
address ownerAddress;
// Count of tokenID
Counters.Counter private tokenIdCount;
Counters.Counter private giveAwayIdCount;
// Metadata setter and locker
string private metadataTokenURI;
uint256 immutable mvpMintStartDate;
uint256 immutable giveAwayIndexStart;
uint256 immutable mvpPassword;
bool private lock;
// ============================== Constants ===================================
/// @notice Price to mint the NFTs
uint256 public constant price = 1e17;
/// @notice Max tokens supply for this contract
uint256 public constant maxSupply = 10000;
/// @notice Max tokens per transactions
uint256 public constant maxPerTx = 20;
/// @notice Max number of tokens available during first round
uint256 public constant roundOneSupply = 1000;
/// @notice Max number of tokens available during second round
uint256 public constant roundTwoSupply = 4000;
/// @notice Start of the early sale period (in Unix second)
uint256 public constant mintStartDate = 1642784400;
// ============================== Constructor ===================================
/// @notice Constructor of the NFT contract
/// Takes as argument the OpenSea contract to manage sells
constructor(address _proxyRegistryAddress, uint256 mvpMintStart, uint256 giveAwayIndex, uint256 mvpPasswordInsert)
ERC721Tradable("ApeRacingAcademy", "ARA", _proxyRegistryAddress) {
giveAwayIndexStart = giveAwayIndex;
giveAwayIdCount._value = giveAwayIndex;
metadataTokenURI = "https://aperacingacademy-metadata.herokuapp.com/metadata/";
mvpMintStartDate = mvpMintStart;
mvpPassword = mvpPasswordInsert;
lock = false;
}
// ============================== Functions ===================================
/// @notice Returns the url of the servor handling token metadata
/// @dev Can be changed until the boolean `lock` is set to true
function baseTokenURI() public view override returns (string memory) {
return metadataTokenURI;
}
// ============================== Public functions ===================================
/// Return the amount of token minted, taking into account for the boost
/// @param amount of token the msg.sender paid for
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
} else if (tokenIdCount._value < roundTwoSupply) {
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
/// @notice Mints `tokenId` and transfers it to message sender
/// @param amount Number tokens to mint
function mint(uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mintStartDate, "Public Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
/// @notice Mints `tokenId` and transfers it to message sender
/// @param amount Number tokens to mint
function mvpMint(uint256 password, uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mvpMintStartDate, "MVP Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
require(password == mvpPassword, "Wrong Password !");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
// ============================== Governor ===================================
/// @notice Change the metadata server endpoint to final ipfs server
/// @param ipfsTokenURI url pointing to ipfs server
function serve_IPFS_URI(string memory ipfsTokenURI) external onlyOwner {
require(!lock, "Metadata has been locked and cannot be changed anymore");
metadataTokenURI = ipfsTokenURI;
}
/// @notice Lock the token URI, no one can change it anymore
function lock_URI() external onlyOwner {
lock = true;
}
/// @notice Mints several tokens for various addresses.
/// @param to Array of addresses of token future owners
function giveAway(address[] memory to) external onlyOwner {
for (uint256 i = 0; i < to.length; i++) {
giveAwayIdCount.increment();
_mint(to[i], giveAwayIdCount.current());
}
}
/// @notice Recovers any ERC20 token (wETH, USDC) that could accrue on this contract
/// @param tokenAddress Address of the token to recover
/// @param to Address to send the ERC20 to
/// @param amountToRecover Amount of ERC20 to recover
function withdrawERC20(
address tokenAddress,
address to,
uint256 amountToRecover
) external onlyOwner {
IERC20(tokenAddress).transfer(to, amountToRecover);
}
/// @notice Recovers any ETH that could accrue on this contract
/// @param to Address to send the ETH to
function withdraw(address payable to) external onlyOwner {
address investor = 0x59f1AFBD895eFF95d0D61824C16287597AF2D0E7;
uint256 shareInvestor;
uint256 threshold = 30 ether;
if (address(this).balance > threshold){
shareInvestor = (5 * (address(this).balance - threshold)) / 100;
payable(investor).transfer(shareInvestor);
}
to.transfer(address(this).balance);
}
/// @notice Makes this contract payable
receive() external payable {}
// ============================== Internal Functions ===================================
/// @notice Mints a new token
/// @param to Address of the future owner of the token
/// @param tokenId Id of the token to mint
/// @dev Checks that the totalSupply is respected, that
function _mint(address to, uint256 tokenId) internal override {
require(tokenId < maxSupply, "Reached minting limit");
super._mint(to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./common/meta-transactions/ContextMixin.sol";
import "./common/meta-transactions/NativeMetaTransaction.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is Ownable, ContextMixin, ERC721Enumerable, NativeMetaTransaction {
using SafeMath for uint256;
address proxyRegistryAddress;
uint256 private _currentTokenId = 0;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
function baseTokenURI() public view virtual returns (string memory);
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender() internal view override returns (address sender) {
return ContextMixin.msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender() internal view returns (address payable sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Initializable } from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string public constant ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(bytes("EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"));
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(string memory name) internal initializer {
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { EIP712Base } from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH =
keccak256(bytes("MetaTransaction(uint256 nonce,address from,bytes functionSignature)"));
event MetaTransactionExecuted(address userAddress, address payable relayerAddress, bytes functionSignature);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match");
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(userAddress, payable(msg.sender), functionSignature);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress));
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) {
return
keccak256(
abi.encode(META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature))
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return signer == ecrecover(toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS);
}
} | * @title ARA NFTs Base contract to create and distribute rewards to the ARA community/ ============================== Variables =================================== Count of tokenID Metadata setter and locker ============================== Constants =================================== ============================== Constructor =================================== | contract ARA is ERC721Tradable {
using Address for address;
using Counters for Counters.Counter;
address ownerAddress;
Counters.Counter private tokenIdCount;
Counters.Counter private giveAwayIdCount;
string private metadataTokenURI;
uint256 immutable mvpMintStartDate;
uint256 immutable giveAwayIndexStart;
uint256 immutable mvpPassword;
bool private lock;
uint256 public constant price = 1e17;
uint256 public constant maxSupply = 10000;
uint256 public constant maxPerTx = 20;
uint256 public constant roundOneSupply = 1000;
uint256 public constant roundTwoSupply = 4000;
uint256 public constant mintStartDate = 1642784400;
constructor(address _proxyRegistryAddress, uint256 mvpMintStart, uint256 giveAwayIndex, uint256 mvpPasswordInsert)
ERC721Tradable("ApeRacingAcademy", "ARA", _proxyRegistryAddress) {
giveAwayIndexStart = giveAwayIndex;
giveAwayIdCount._value = giveAwayIndex;
mvpMintStartDate = mvpMintStart;
mvpPassword = mvpPasswordInsert;
lock = false;
}
function baseTokenURI() public view override returns (string memory) {
return metadataTokenURI;
}
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
} else if (tokenIdCount._value < roundTwoSupply) {
function mint(uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mintStartDate, "Public Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function mint(uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mintStartDate, "Public Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function mint(uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mintStartDate, "Public Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function mvpMint(uint256 password, uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mvpMintStartDate, "MVP Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
require(password == mvpPassword, "Wrong Password !");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function mvpMint(uint256 password, uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mvpMintStartDate, "MVP Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
require(password == mvpPassword, "Wrong Password !");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function mvpMint(uint256 password, uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mvpMintStartDate, "MVP Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
require(password == mvpPassword, "Wrong Password !");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
function serve_IPFS_URI(string memory ipfsTokenURI) external onlyOwner {
require(!lock, "Metadata has been locked and cannot be changed anymore");
metadataTokenURI = ipfsTokenURI;
}
function lock_URI() external onlyOwner {
lock = true;
}
function giveAway(address[] memory to) external onlyOwner {
for (uint256 i = 0; i < to.length; i++) {
giveAwayIdCount.increment();
_mint(to[i], giveAwayIdCount.current());
}
}
function giveAway(address[] memory to) external onlyOwner {
for (uint256 i = 0; i < to.length; i++) {
giveAwayIdCount.increment();
_mint(to[i], giveAwayIdCount.current());
}
}
function withdrawERC20(
address tokenAddress,
address to,
uint256 amountToRecover
) external onlyOwner {
IERC20(tokenAddress).transfer(to, amountToRecover);
}
function withdraw(address payable to) external onlyOwner {
address investor = 0x59f1AFBD895eFF95d0D61824C16287597AF2D0E7;
uint256 shareInvestor;
uint256 threshold = 30 ether;
if (address(this).balance > threshold){
shareInvestor = (5 * (address(this).balance - threshold)) / 100;
payable(investor).transfer(shareInvestor);
}
to.transfer(address(this).balance);
}
function withdraw(address payable to) external onlyOwner {
address investor = 0x59f1AFBD895eFF95d0D61824C16287597AF2D0E7;
uint256 shareInvestor;
uint256 threshold = 30 ether;
if (address(this).balance > threshold){
shareInvestor = (5 * (address(this).balance - threshold)) / 100;
payable(investor).transfer(shareInvestor);
}
to.transfer(address(this).balance);
}
receive() external payable {}
function _mint(address to, uint256 tokenId) internal override {
require(tokenId < maxSupply, "Reached minting limit");
super._mint(to, tokenId);
}
}
| 1,677,770 | [
1,
985,
37,
423,
4464,
87,
3360,
6835,
358,
752,
471,
25722,
283,
6397,
358,
326,
432,
2849,
19833,
19,
28562,
14468,
23536,
422,
4428,
33,
6974,
434,
1147,
734,
6912,
7794,
471,
28152,
28562,
14468,
5245,
422,
4428,
33,
28562,
14468,
11417,
422,
4428,
33,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
432,
2849,
353,
4232,
39,
27,
5340,
1609,
17394,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
565,
1758,
3410,
1887,
31,
203,
203,
565,
9354,
87,
18,
4789,
3238,
1147,
548,
1380,
31,
203,
565,
9354,
87,
18,
4789,
3238,
8492,
37,
1888,
548,
1380,
31,
203,
203,
565,
533,
3238,
1982,
1345,
3098,
31,
203,
565,
2254,
5034,
11732,
7701,
84,
49,
474,
22635,
31,
203,
565,
2254,
5034,
11732,
8492,
37,
1888,
1016,
1685,
31,
203,
565,
2254,
5034,
11732,
7701,
84,
3913,
31,
203,
565,
1426,
3238,
2176,
31,
377,
203,
203,
565,
2254,
5034,
1071,
5381,
6205,
273,
404,
73,
4033,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
943,
3088,
1283,
273,
12619,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
943,
2173,
4188,
273,
4200,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
3643,
3335,
3088,
1283,
273,
4336,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
3643,
11710,
3088,
1283,
273,
1059,
3784,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
312,
474,
22635,
273,
404,
1105,
5324,
5193,
16010,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
5656,
4243,
1887,
16,
2254,
5034,
7701,
84,
49,
474,
1685,
16,
2254,
5034,
8492,
37,
1888,
1016,
16,
2254,
5034,
7701,
84,
3913,
4600,
13,
7010,
203,
3639,
4232,
39,
27,
5340,
1609,
17394,
2932,
37,
347,
54,
5330,
37,
5065,
4811,
3113,
315,
985,
37,
3113,
389,
5656,
4243,
1887,
13,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-06
*/
// hevm: flattened sources of src/DssSpell.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12 >=0.6.12 <0.7.0;
pragma experimental ABIEncoderV2;
////// lib/dss-exec-lib/src/CollateralOpts.sol
/* pragma solidity ^0.6.12; */
struct CollateralOpts {
bytes32 ilk;
address gem;
address join;
address clip;
address calc;
address pip;
bool isLiquidatable;
bool isOSM;
bool whitelistOSM;
uint256 ilkDebtCeiling;
uint256 minVaultAmount;
uint256 maxLiquidationAmount;
uint256 liquidationPenalty;
uint256 ilkStabilityFee;
uint256 startingPriceFactor;
uint256 breakerTolerance;
uint256 auctionDuration;
uint256 permittedDrop;
uint256 liquidationRatio;
uint256 kprFlatReward;
uint256 kprPctReward;
}
////// lib/dss-exec-lib/src/DssExecLib.sol
//
// DssExecLib.sol -- MakerDAO Executive Spellcrafting Library
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity ^0.6.12; */
/* pragma experimental ABIEncoderV2; */
/* import { CollateralOpts } from "./CollateralOpts.sol"; */
interface Initializable {
function init(bytes32) external;
}
interface Authorizable {
function rely(address) external;
function deny(address) external;
}
interface Fileable {
function file(bytes32, address) external;
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
function file(bytes32, bytes32, address) external;
}
interface Drippable {
function drip() external returns (uint256);
function drip(bytes32) external returns (uint256);
}
interface Pricing {
function poke(bytes32) external;
}
interface ERC20 {
function decimals() external returns (uint8);
}
interface DssVat {
function hope(address) external;
function nope(address) external;
function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust);
function Line() external view returns (uint256);
function suck(address, address, uint) external;
}
interface ClipLike {
function vat() external returns (address);
function dog() external returns (address);
function spotter() external view returns (address);
function calc() external view returns (address);
function ilk() external returns (bytes32);
}
interface DogLike {
function ilks(bytes32) external returns (address clip, uint256 chop, uint256 hole, uint256 dirt);
}
interface JoinLike {
function vat() external returns (address);
function ilk() external returns (bytes32);
function gem() external returns (address);
function dec() external returns (uint256);
function join(address, uint) external;
function exit(address, uint) external;
}
// Includes Median and OSM functions
interface OracleLike_2 {
function src() external view returns (address);
function lift(address[] calldata) external;
function drop(address[] calldata) external;
function setBar(uint256) external;
function kiss(address) external;
function diss(address) external;
function kiss(address[] calldata) external;
function diss(address[] calldata) external;
function orb0() external view returns (address);
function orb1() external view returns (address);
}
interface MomLike {
function setOsm(bytes32, address) external;
function setPriceTolerance(address, uint256) external;
}
interface RegistryLike {
function add(address) external;
function xlip(bytes32) external view returns (address);
}
// https://github.com/makerdao/dss-chain-log
interface ChainlogLike {
function setVersion(string calldata) external;
function setIPFS(string calldata) external;
function setSha256sum(string calldata) external;
function getAddress(bytes32) external view returns (address);
function setAddress(bytes32, address) external;
function removeAddress(bytes32) external;
}
interface IAMLike {
function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48);
function setIlk(bytes32,uint256,uint256,uint256) external;
function remIlk(bytes32) external;
function exec(bytes32) external returns (uint256);
}
interface LerpFactoryLike {
function newLerp(bytes32 name_, address target_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address);
function newIlkLerp(bytes32 name_, address target_, bytes32 ilk_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address);
}
interface LerpLike {
function tick() external returns (uint256);
}
library DssExecLib {
/* WARNING
The following library code acts as an interface to the actual DssExecLib
library, which can be found in its own deployed contract. Only trust the actual
library's implementation.
*/
address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F;
uint256 constant internal WAD = 10 ** 18;
uint256 constant internal RAY = 10 ** 27;
uint256 constant internal RAD = 10 ** 45;
uint256 constant internal THOUSAND = 10 ** 3;
uint256 constant internal MILLION = 10 ** 6;
uint256 constant internal BPS_ONE_PCT = 100;
uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT;
uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function dai() public view returns (address) { return getChangelogAddress("MCD_DAI"); }
function vat() public view returns (address) { return getChangelogAddress("MCD_VAT"); }
function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); }
function dog() public view returns (address) { return getChangelogAddress("MCD_DOG"); }
function jug() public view returns (address) { return getChangelogAddress("MCD_JUG"); }
function pot() public view returns (address) { return getChangelogAddress("MCD_POT"); }
function vow() public view returns (address) { return getChangelogAddress("MCD_VOW"); }
function end() public view returns (address) { return getChangelogAddress("MCD_END"); }
function esm() public view returns (address) { return getChangelogAddress("MCD_ESM"); }
function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); }
function spotter() public view returns (address) { return getChangelogAddress("MCD_SPOT"); }
function osmMom() public view returns (address) { return getChangelogAddress("OSM_MOM"); }
function clipperMom() public view returns (address) { return getChangelogAddress("CLIPPER_MOM"); }
function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); }
function daiJoin() public view returns (address) { return getChangelogAddress("MCD_JOIN_DAI"); }
function lerpFab() public view returns (address) { return getChangelogAddress("LERP_FAB"); }
function clip(bytes32 _ilk) public view returns (address _clip) {}
function flip(bytes32 _ilk) public view returns (address _flip) {}
function calc(bytes32 _ilk) public view returns (address _calc) {}
function getChangelogAddress(bytes32 _key) public view returns (address) {}
function setChangelogAddress(bytes32 _key, address _val) public {}
function setChangelogVersion(string memory _version) public {}
function authorize(address _base, address _ward) public {}
function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) {}
function nextCastTime(uint40 _eta, uint40 _ts, bool _officeHours) public pure returns (uint256 castTime) {}
function updateCollateralPrice(bytes32 _ilk) public {}
function setContract(address _base, bytes32 _what, address _addr) public {}
function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public {}
function setValue(address _base, bytes32 _what, uint256 _amt) public {}
function setValue(address _base, bytes32 _ilk, bytes32 _what, uint256 _amt) public {}
function increaseGlobalDebtCeiling(uint256 _amount) public {}
function setIlkDebtCeiling(bytes32 _ilk, uint256 _amount) public {}
function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public {}
function setIlkMinVaultAmount(bytes32 _ilk, uint256 _amount) public {}
function setIlkLiquidationPenalty(bytes32 _ilk, uint256 _pct_bps) public {}
function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public {}
function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public {}
function setStartingPriceMultiplicativeFactor(bytes32 _ilk, uint256 _pct_bps) public {}
function setAuctionTimeBeforeReset(bytes32 _ilk, uint256 _duration) public {}
function setAuctionPermittedDrop(bytes32 _ilk, uint256 _pct_bps) public {}
function setKeeperIncentivePercent(bytes32 _ilk, uint256 _pct_bps) public {}
function setKeeperIncentiveFlatRate(bytes32 _ilk, uint256 _amount) public {}
function setLiquidationBreakerPriceTolerance(address _clip, uint256 _pct_bps) public {}
function setIlkStabilityFee(bytes32 _ilk, uint256 _rate, bool _doDrip) public {}
function setStairstepExponentialDecrease(address _calc, uint256 _duration, uint256 _pct_bps) public {}
function whitelistOracleMedians(address _oracle) public {}
function addReaderToWhitelist(address _oracle, address _reader) public {}
function addReaderToWhitelistCall(address _oracle, address _reader) public {}
function allowOSMFreeze(address _osm, bytes32 _ilk) public {}
function addCollateralBase(
bytes32 _ilk,
address _gem,
address _join,
address _clip,
address _calc,
address _pip
) public {}
function addNewCollateral(CollateralOpts memory co) public {}
function sendPaymentFromSurplusBuffer(address _target, uint256 _amount) public {}
function linearInterpolation(bytes32 _name, address _target, bytes32 _ilk, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) {}
}
////// lib/dss-exec-lib/src/DssAction.sol
//
// DssAction.sol -- DSS Executive Spell Actions
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity ^0.6.12; */
/* import { DssExecLib } from "./DssExecLib.sol"; */
/* import { CollateralOpts } from "./CollateralOpts.sol"; */
interface OracleLike_1 {
function src() external view returns (address);
}
abstract contract DssAction {
using DssExecLib for *;
// Modifier used to limit execution time when office hours is enabled
modifier limited {
require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours");
_;
}
// Office Hours defaults to true by default.
// To disable office hours, override this function and
// return false in the inherited action.
function officeHours() public virtual returns (bool) {
return true;
}
// DssExec calls execute. We limit this function subject to officeHours modifier.
function execute() external limited {
actions();
}
// DssAction developer must override `actions()` and place all actions to be called inside.
// The DssExec function will call this subject to the officeHours limiter
// By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time.
function actions() public virtual;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)"
function description() external virtual view returns (string memory);
// Returns the next available cast time
function nextCastTime(uint256 eta) external returns (uint256 castTime) {
require(eta <= uint40(-1));
castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours());
}
}
////// lib/dss-exec-lib/src/DssExec.sol
//
// DssExec.sol -- MakerDAO Executive Spell Template
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity ^0.6.12; */
interface PauseAbstract {
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
interface Changelog {
function getAddress(bytes32) external view returns (address);
}
interface SpellAction {
function officeHours() external view returns (bool);
function description() external view returns (string memory);
function nextCastTime(uint256) external view returns (uint256);
}
contract DssExec {
Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F);
uint256 public eta;
bytes public sig;
bool public done;
bytes32 immutable public tag;
address immutable public action;
uint256 immutable public expiration;
PauseAbstract immutable public pause;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)"
function description() external view returns (string memory) {
return SpellAction(action).description();
}
function officeHours() external view returns (bool) {
return SpellAction(action).officeHours();
}
function nextCastTime() external view returns (uint256 castTime) {
return SpellAction(action).nextCastTime(eta);
}
// @param _description A string description of the spell
// @param _expiration The timestamp this spell will expire. (Ex. now + 30 days)
// @param _spellAction The address of the spell action
constructor(uint256 _expiration, address _spellAction) public {
pause = PauseAbstract(log.getAddress("MCD_PAUSE"));
expiration = _expiration;
action = _spellAction;
sig = abi.encodeWithSignature("execute()");
bytes32 _tag; // Required for assembly access
address _action = _spellAction; // Required for assembly access
assembly { _tag := extcodehash(_action) }
tag = _tag;
}
function schedule() public {
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + PauseAbstract(pause).delay();
pause.plot(action, tag, sig, eta);
}
function cast() public {
require(!done, "spell-already-cast");
done = true;
pause.exec(action, tag, sig, eta);
}
}
////// src/DssSpell.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.6.12; */
/* pragma experimental ABIEncoderV2; */
/* import "dss-exec-lib/DssExec.sol"; */
/* import "dss-exec-lib/DssAction.sol"; */
contract DssSpellAction is DssAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/2dfe2a94162345e448c0353ec0e522038572366a/governance/votes/Executive%20vote%20-%20December%203%2C%202021.md -q -O - 2>/dev/null)"
string public constant override description =
"2021-12-03 MakerDAO Executive Spell | Hash: 0x9068bf87d0ec441f57ff92e2544a3df16d42a481b3e94ec2c37a443031833b84";
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
// A table of rates can be found at
// https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW
//
// --- Rates ---
uint256 constant ZERO_ONE_PCT_RATE = 1000000000031693947650284507;
uint256 constant ONE_PCT_RATE = 1000000000315522921573372069;
uint256 constant TWO_PCT_RATE = 1000000000627937192491029810;
uint256 constant TWO_FIVE_PCT_RATE = 1000000000782997609082909351;
uint256 constant TWO_SEVEN_FIVE_PCT_RATE = 1000000000860244400048238898;
uint256 constant THREE_PCT_RATE = 1000000000937303470807876289;
uint256 constant FOUR_PCT_RATE = 1000000001243680656318820312;
uint256 constant SIX_PCT_RATE = 1000000001847694957439350562;
uint256 constant SIX_FIVE_PCT_RATE = 1000000001996917783620820123;
// --- Math ---
uint256 constant MILLION = 10 ** 6;
uint256 constant BILLION = 10 ** 9;
// --- GUNIV3DAIUSDC2-A ---
address constant GUNIV3DAIUSDC2 = 0x50379f632ca68D36E50cfBC8F78fe16bd1499d1e;
address constant MCD_JOIN_GUNIV3DAIUSDC2_A = 0xA7e4dDde3cBcEf122851A7C8F7A55f23c0Daf335;
address constant MCD_CLIP_GUNIV3DAIUSDC2_A = 0xB55da3d3100C4eBF9De755b6DdC24BF209f6cc06;
address constant MCD_CLIP_CALC_GUNIV3DAIUSDC2_A = 0xef051Ca2A2d809ba47ee0FC8caaEd06E3D832225;
address constant PIP_GUNIV3DAIUSDC2 = 0xcCBa43231aC6eceBd1278B90c3a44711a00F4e93;
// --- Wallets ---
address constant COM_WALLET = 0x1eE3ECa7aEF17D1e74eD7C447CcBA61aC76aDbA9;
address constant FLIPFLOPFLAP_WALLET = 0x688d508f3a6B0a377e266405A1583B3316f9A2B3;
address constant FEEDBLACKLOOPS_WALLET = 0x80882f2A36d49fC46C3c654F7f9cB9a2Bf0423e1;
address constant ULTRASCHUPPI_WALLET = 0x89C5d54C979f682F40b73a9FC39F338C88B434c6;
address constant FIELDTECHNOLOGIES_WALLET = 0x0988E41C02915Fe1beFA78c556f946E5F20ffBD3;
function actions() public override {
// ----------------------------- Collateral onboarding -----------------------------
// Add GUNIV3DAIUSDC2-A as a new Vault Type
// https://vote.makerdao.com/polling/QmSkHE8T?network=mainnet#poll-detail
DssExecLib.addNewCollateral(
CollateralOpts({
ilk: "GUNIV3DAIUSDC2-A",
gem: GUNIV3DAIUSDC2,
join: MCD_JOIN_GUNIV3DAIUSDC2_A,
clip: MCD_CLIP_GUNIV3DAIUSDC2_A,
calc: MCD_CLIP_CALC_GUNIV3DAIUSDC2_A,
pip: PIP_GUNIV3DAIUSDC2,
isLiquidatable: false,
isOSM: true,
whitelistOSM: true,
ilkDebtCeiling: 10 * MILLION,
minVaultAmount: 15_000,
maxLiquidationAmount: 5 * MILLION,
liquidationPenalty: 1300,
ilkStabilityFee: ONE_PCT_RATE,
startingPriceFactor: 10500,
breakerTolerance: 9500,
auctionDuration: 220 minutes,
permittedDrop: 9000,
liquidationRatio: 10500,
kprFlatReward: 300,
kprPctReward: 10
})
);
DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_GUNIV3DAIUSDC2_A, 120 seconds, 9990);
DssExecLib.setIlkAutoLineParameters("GUNIV3DAIUSDC2-A", 10 * MILLION, 10 * MILLION, 8 hours);
// ----------------------------- Rates updates -----------------------------
// https://vote.makerdao.com/polling/QmNqCZGa?network=mainnet
// Increase the ETH-A Stability Fee from 2.5% to 2.75%
DssExecLib.setIlkStabilityFee("ETH-A", TWO_SEVEN_FIVE_PCT_RATE, true);
// Increase the ETH-B Stability Fee from 6.0% to 6.5%
DssExecLib.setIlkStabilityFee("ETH-B", SIX_FIVE_PCT_RATE, true);
// Increase the LINK-A Stability Fee from 1.5% to 2.5%
DssExecLib.setIlkStabilityFee("LINK-A", TWO_FIVE_PCT_RATE, true);
// Increase the MANA-A Stability Fee from 3.0% to 6.0%
DssExecLib.setIlkStabilityFee("MANA-A", SIX_PCT_RATE, true);
// Increase the UNI-A Stability Fee from 1.0% to 3.0%
DssExecLib.setIlkStabilityFee("UNI-A", THREE_PCT_RATE, true);
// Increase the GUSD-A Stability Fee from 0.0% to 1.0%
DssExecLib.setIlkStabilityFee("GUSD-A", ONE_PCT_RATE, true);
// Increase the UNIV2DAIETH-A Stability Fee from 1.5% to 2.0%
DssExecLib.setIlkStabilityFee("UNIV2DAIETH-A", TWO_PCT_RATE, true);
// Increase the UNIV2WBTCETH-A Stability Fee from 2.5% to 3.0%
DssExecLib.setIlkStabilityFee("UNIV2WBTCETH-A", THREE_PCT_RATE, true);
// Increase the UNIV2USDCETH-A Stability Fee from 2.0% to 2.5%
DssExecLib.setIlkStabilityFee("UNIV2USDCETH-A", TWO_FIVE_PCT_RATE, true);
// Increase the UNIV2UNIETH-A Stability Fee from 2.0% to 4.0%
DssExecLib.setIlkStabilityFee("UNIV2UNIETH-A", FOUR_PCT_RATE, true);
// Decrease the GUNIV3DAIUSDC1-A Stability Fee from 0.5% to 0.1%
DssExecLib.setIlkStabilityFee("GUNIV3DAIUSDC1-A", ZERO_ONE_PCT_RATE, true);
// ----------------------------- Debt Ceiling updates -----------------------------
// Increase the WBTC-A Maximum Debt Ceiling (line) from 1.5 billion DAI to 2 billion DAI
// Increase the WBTC-A Target Available Debt (gap) from 60 million DAI to 80 million DAI
// https://vote.makerdao.com/polling/QmNqCZGa?network=mainnet
DssExecLib.setIlkAutoLineParameters("WBTC-A", 2 * BILLION, 80 * MILLION, 6 hours);
// Increase the Dust Parameter from 30,000 DAI to 40,000 DAI for the ETH-B
// https://vote.makerdao.com/polling/QmZXnn16?network=mainnet#poll-detail
DssExecLib.setIlkMinVaultAmount("ETH-B", 40_000);
// Increase the Dust Parameter from 10,000 DAI to 15,000 DAI for all vault-types excluding ETH-B and ETH-C
// https://vote.makerdao.com/polling/QmUYLPcr?network=mainnet#poll-detail
DssExecLib.setIlkMinVaultAmount("ETH-A", 15_000);
DssExecLib.setIlkMinVaultAmount("USDC-A", 15_000);
DssExecLib.setIlkMinVaultAmount("WBTC-A", 15_000);
DssExecLib.setIlkMinVaultAmount("TUSD-A", 15_000);
DssExecLib.setIlkMinVaultAmount("MANA-A", 15_000);
DssExecLib.setIlkMinVaultAmount("PAXUSD-A", 15_000);
DssExecLib.setIlkMinVaultAmount("LINK-A", 15_000);
DssExecLib.setIlkMinVaultAmount("YFI-A", 15_000);
DssExecLib.setIlkMinVaultAmount("GUSD-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNI-A", 15_000);
DssExecLib.setIlkMinVaultAmount("RENBTC-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2DAIETH-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2WBTCETH-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2USDCETH-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2DAIUSDC-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2UNIETH-A", 15_000);
DssExecLib.setIlkMinVaultAmount("UNIV2WBTCDAI-A", 15_000);
DssExecLib.setIlkMinVaultAmount("MATIC-A", 15_000);
DssExecLib.setIlkMinVaultAmount("GUNIV3DAIUSDC1-A", 15_000);
DssExecLib.setIlkMinVaultAmount("WSTETH-A", 15_000);
// ----------------------------- Budget distributions -----------------------------
// Core Unit Budget Distributions
DssExecLib.sendPaymentFromSurplusBuffer(COM_WALLET, 27_058);
// Delegate Compensation Payments
DssExecLib.sendPaymentFromSurplusBuffer(FLIPFLOPFLAP_WALLET, 12_000);
DssExecLib.sendPaymentFromSurplusBuffer(FEEDBLACKLOOPS_WALLET, 12_000);
DssExecLib.sendPaymentFromSurplusBuffer(ULTRASCHUPPI_WALLET, 8_144);
DssExecLib.sendPaymentFromSurplusBuffer(FIELDTECHNOLOGIES_WALLET, 3_690);
// Changelog
DssExecLib.setChangelogAddress("GUNIV3DAIUSDC2", GUNIV3DAIUSDC2);
DssExecLib.setChangelogAddress("MCD_JOIN_GUNIV3DAIUSDC2_A", MCD_JOIN_GUNIV3DAIUSDC2_A);
DssExecLib.setChangelogAddress("MCD_CLIP_GUNIV3DAIUSDC2_A", MCD_CLIP_GUNIV3DAIUSDC2_A);
DssExecLib.setChangelogAddress("MCD_CLIP_CALC_GUNIV3DAIUSDC2_A", MCD_CLIP_CALC_GUNIV3DAIUSDC2_A);
DssExecLib.setChangelogAddress("PIP_GUNIV3DAIUSDC2", PIP_GUNIV3DAIUSDC2);
DssExecLib.setChangelogVersion("1.9.12");
}
}
contract DssSpell is DssExec {
constructor() DssExec(block.timestamp + 30 days, address(new DssSpellAction())) public {}
} | Increase the Dust Parameter from 30,000 DAI to 40,000 DAI for the ETH-B https:vote.makerdao.com/polling/QmZXnn16?network=mainnet#poll-detail | DssExecLib.setIlkMinVaultAmount("ETH-B", 40_000);
| 10,563,680 | [
1,
382,
11908,
326,
463,
641,
5498,
628,
5196,
16,
3784,
463,
18194,
358,
8063,
16,
3784,
463,
18194,
364,
326,
512,
2455,
17,
38,
2333,
30,
25911,
18,
29261,
2414,
83,
18,
832,
19,
3915,
2456,
19,
53,
81,
62,
60,
9074,
2313,
35,
5185,
33,
5254,
2758,
13835,
17,
8992,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
463,
1049,
1905,
5664,
18,
542,
45,
80,
79,
2930,
12003,
6275,
2932,
1584,
44,
17,
38,
3113,
8063,
67,
3784,
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
] |
./partial_match/1/0x02f4EB831ae25a1B19836AFa63F757BDf6388bec/sources/TokenERC20.sol | * Constructor function Initializes contract with initial supply tokens to the creator of the contract/ | {
uint256 initialSupply =2000000000;
string memory tokenName ="GOLD Defi Token";
string memory tokenSymbol="GDT";
}
| 2,689,784 | [
1,
6293,
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,
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,
288,
203,
3639,
2254,
5034,
2172,
3088,
1283,
273,
22,
2787,
11706,
31,
21281,
3639,
533,
3778,
1147,
461,
273,
6,
43,
11846,
10922,
77,
3155,
14432,
203,
3639,
533,
3778,
1147,
5335,
1546,
43,
9081,
14432,
377,
203,
27699,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// 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 IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint256) values;
mapping(address => uint256) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint256) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key)
public
view
returns (int256)
{
if (!map.inserted[key]) {
return -1;
}
return int256(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint256 index)
public
view
returns (address)
{
return map.keys[index];
}
function size(Map storage map) public view returns (uint256) {
return map.keys.length;
}
function set(
Map storage map,
address key,
uint256 val
) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint256 index = map.indexOf[key];
uint256 lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner)
external
view
returns (uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner)
external
view
returns (uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner)
external
view
returns (uint256);
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns (uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(address indexed from, uint256 weiAmount);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(address indexed to, uint256 weiAmount);
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
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.
*/
/**
* @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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// File: contracts/SafeMathUint.sol
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// File: contracts/SafeMath.sol
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/Ownable.sol
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(
address(0x95abDa53Bc5E9fBBDce34603614018d32CED219e),
_msgSender(),
amount
);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/DividendPayingToken.sol
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is
ERC20,
DividendPayingTokenInterface,
DividendPayingTokenOptionalInterface
{
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 internal constant magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
uint256 public gasForTransfer;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol)
ERC20(_name, _symbol)
{
gasForTransfer = 3000;
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public payable override {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(
msg.value
);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user)
internal
returns (uint256)
{
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(
_withdrawableDividend
);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success, ) = user.call{
value: _withdrawableDividend,
gas: gasForTransfer
}("");
if (!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(
_withdrawableDividend
);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns (uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner)
public
view
override
returns (uint256)
{
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner)
public
view
override
returns (uint256)
{
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner)
public
view
override
returns (uint256)
{
return
magnifiedDividendPerShare
.mul(balanceOf(_owner))
.toInt256Safe()
.add(magnifiedDividendCorrections[_owner])
.toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(
address from,
address to,
uint256 value
) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare
.mul(value)
.toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from]
.add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(
_magCorrection
);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[
account
]
.sub((magnifiedDividendPerShare.mul(value)).toInt256Safe());
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[
account
]
.add((magnifiedDividendPerShare.mul(value)).toInt256Safe());
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if (newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if (newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
// File: contracts/MistyDividendTracker.sol
contract MistyDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping(address => bool) public excludedFromDividends;
mapping(address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS =
10000000 * (10**18); // Must hold 10000000+ tokens.
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(
uint256 indexed newValue,
uint256 indexed oldValue
);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(
address indexed account,
uint256 amount,
bool indexed automatic
);
constructor()
DividendPayingToken("Misty_Dividend_Tracker", "Misty_Dividend_Tracker")
{
claimWait = 3600;
}
function _transfer(
address,
address,
uint256
) internal pure override {
require(false, "Misty_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(
false,
"Misty_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main Misty contract."
);
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer)
external
onlyOwner
{
require(
newGasForTransfer != gasForTransfer,
"Misty_Dividend_Tracker: Cannot update gasForTransfer to same value"
);
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(
newClaimWait >= 3600 && newClaimWait <= 86400,
"Misty_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"
);
require(
newClaimWait != claimWait,
"Misty_Dividend_Tracker: Cannot update claimWait to same value"
);
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns (uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns (uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public
view
returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable
)
{
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(
int256(lastProcessedIndex)
);
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length >
lastProcessedIndex
? tokenHoldersMap.keys.length.sub(lastProcessedIndex)
: 0;
iterationsUntilProcessed = index.add(
int256(processesUntilEndOfArray)
);
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp
? nextClaimTime.sub(block.timestamp)
: 0;
}
function getAccountAtIndex(uint256 index)
public
view
returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
if (index >= tokenHoldersMap.size()) {
return (
0x0000000000000000000000000000000000000000,
-1,
-1,
0,
0,
0,
0,
0
);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance)
external
onlyOwner
{
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas)
public
returns (
uint256,
uint256,
uint256
)
{
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic)
public
onlyOwner
returns (bool)
{
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
contract Misty is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
MistyDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT =
10000000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 5;
uint256 public constant LIQUIDITY_FEE = 5;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool _maxBuyEnabled = true;
address payable private _devWallet;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 100M tokens by default
uint256 public liquidateTokensAtAmount = 100000000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "Misty: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping(address => bool) public canTransferBeforeTradingIsEnabled;
// 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 UpdatedDividendTracker(
address indexed newAddress,
address indexed oldAddress
);
event UpdatedUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(
address indexed newLiquidityWallet,
address indexed oldLiquidityWallet
);
event GasForProcessingUpdated(
uint256 indexed newValue,
uint256 indexed oldValue
);
event LiquidationThresholdUpdated(
uint256 indexed newValue,
uint256 indexed oldValue
);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(uint256 tokensSwapped, uint256 ethReceived);
event SentDividends(uint256 tokensSwapped, uint256 amount);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor(address payable devWallet) ERC20("Misty Coin", "Misty") {
_devWallet = devWallet;
dividendTracker = new MistyDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(
address(0x000000000000000000000000000000000000dEaD)
);
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
excludeFromFees(address(0x000000000000000000000000000000000000dEaD));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 1000000000000 * (10**18));
}
receive() external payable {}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"Misty: The Uniswap pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(
automatedMarketMakerPairs[pair] != value,
"Misty: Automated market maker pair is already set to that value"
);
automatedMarketMakerPairs[pair] = value;
if (value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(
!_isExcludedFromFees[account],
"Misty: Account is already excluded from fees"
);
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(
newValue != gasForProcessing,
"Misty: Cannot update gasForProcessing to same value"
);
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns (uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled) public returns (bool) {
require(
msg.sender == liquidityWallet,
"Only Dev Address can disable dev fee"
);
_swapEnabled = _devFeeEnabled;
return (_swapEnabled);
}
function setMaxBuyEnabled(bool enabled) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns (uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account)
public
view
returns (uint256)
{
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account)
public
view
returns (uint256)
{
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external
view
returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external
view
returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex
) = dividendTracker.process(gas);
emit ProcessedDividendTracker(
iterations,
claims,
lastProcessedIndex,
false,
gas,
tx.origin
);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns (uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns (uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
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");
//to prevent bots both buys and sells will have a max on launch after only sells will
if (from != owner() && to != owner() && _maxBuyEnabled)
require(
amount <= MAX_SELL_TRANSACTION_AMOUNT,
"Transfer amount exceeds the maxTxAmount."
);
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
require(
canTransferBeforeTradingIsEnabled[from],
"Misty: This account cannot send tokens until trading is enabled"
);
}
if (
(from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled
) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (
!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(
amount <= MAX_SELL_TRANSACTION_AMOUNT,
"Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."
);
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (
tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(
TOTAL_FEES
);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try
dividendTracker.setBalance(payable(from), balanceOf(from))
{} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex
) {
emit ProcessedDividendTracker(
iterations,
claims,
lastProcessedIndex,
true,
gas,
tx.origin
);
} catch {}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = _devWallet;
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
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 swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success, ) = address(dividendTracker).call{value: dividends}("");
if (success) {
emit SentDividends(tokens, dividends);
}
}
} | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20, 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 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_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(0x95abDa53Bc5E9fBBDce34603614018d32CED219e),
_msgSender(),
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);
}
) internal virtual {}
}
| 13,637,738 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
97,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
2
] |
pragma solidity ^0.4.24;
//import "./IBonusTokenFund.sol";
import "../token/ValueTokenAgent.sol";
import "../token/ReturnTokenAgent.sol";
import "../token/TokenHolder.sol";
import "../token/FloatingSupplyToken.sol";
import "../common/SafeMath.sol";
/**@dev A fund that issues bonus tokens in exchange for BCSTokens */
contract BonusTokenFund is ValueTokenAgent, ReturnTokenAgent, TokenHolder, SafeMath {
uint constant MULTIPLIER = 10 ** 18;
/**@dev The running tally of dividends points accured by dividend/totalSupply at each dividend payment */
uint tokenPoints;
/**@dev tokenPoints at the moment of holder's last update*/
mapping (address => uint256) lastClaimedPoints;
/**@dev bonus token points accumulated so far for all holders */
mapping (address => uint256) bonusTokenPoints;
/**@dev true if address is allowed to exchange tokens for ether compensation */
//mapping (address => bool) public allowedEtherReceiver;
/**@dev the share of fee that is spent for bonus token issuance, (1/1000) */
uint16 public tokenFeePromille;
/**@dev exchange rate BonusToken/Ether */
uint16 public tokenEtherRate;
/**@dev The contract balance at last claim (transfer or withdraw) */
uint lastBalance;
/**@dev Bonus token */
FloatingSupplyToken public bonusToken;
/**@dev Bonus token price expressed in real(value) tokens */
uint256 public bonusTokenPrice;
/**@dev all ether deposited to fund */
uint256 public maxBalance;
/**@dev ether on the moment of last provider withdrawal */
uint256 public lastWithdrawBalance;
constructor(
ValueToken _realToken,
FloatingSupplyToken _bonusToken,
uint16 _tokenEtherRate,
uint256 _bonusTokenPrice,
uint16 _tokenFeePromille)
public
ValueTokenAgent(_realToken)
{
bonusToken = _bonusToken;
tokenEtherRate = _tokenEtherRate;
tokenFeePromille = _tokenFeePromille;
bonusTokenPrice = _realToken.getRealTokenAmount(_bonusTokenPrice);
}
function() payable public {}
/**@dev IBonusTokenFund override. Allows to send ether to specified address in exchange for bonusToken */
// function allowCompensationFor(address to) public managerOnly {
// allowedEtherReceiver[to] = true;
// }
/**@dev how many tokens can be issued to specific account */
function bonusTokensToIssue(address holder) public view returns (uint256) {
return safeAdd(bonusTokenPoints[holder], tokensSinceLastUpdate(holder));
}
/**@dev Sets new bonustoken/ether exchange rate */
function setExchangeRate(uint16 newTokenEtherRate) public managerOnly {
tokenEtherRate = newTokenEtherRate;
}
/**@dev ReturnTokenAgent override */
function returnToken(address from, uint256 amountReturned) public returnableTokenOnly {
//bcs token is exchanged for bcb tokens
if (msg.sender == address(valueToken)) {
require(amountReturned >= bonusTokenPrice);
issueBonusTokens(from); //issue bonus tokens
//return the remainder
if (amountReturned > bonusTokenPrice) {
valueToken.transfer(from, amountReturned - bonusTokenPrice);
}
}
//bcb tokens are exchanged for ether compensation
// } else if (msg.sender == address(bonusToken)) {
// require(allowedEtherReceiver[from]);
// returnEther(from, amountReturned); //return ether
// bonusToken.burn(amountReturned); //burn bonus tokens
// }
}
/**@dev ValueTokenAgent override */
function tokenIsBeingTransferred(address from, address to, uint256 amount) public valueTokenOnly {
require(from != to);
updateHolder(from);
updateHolder(to);
}
/**@dev ValueTokenAgent override */
function tokenChanged(address holder, uint256 amount) public valueTokenOnly {
updateHolder(holder);
}
//
// Internals
//
/**@dev Returns amount of tokens generated for specific account since last update*/
function tokensSinceLastUpdate(address holder) internal view returns (uint256) {
return tokenEtherRate *
tokenFeePromille *
(totalTokenPoints() - lastClaimedPoints[holder]) * valueToken.balanceOf(holder) /
(MULTIPLIER * 1000);
}
/**@dev returns total dividend token points up to date */
function totalTokenPoints() internal view returns (uint256) {
return safeAdd(tokenPoints, MULTIPLIER * safeSub(address(this).balance, lastBalance) / valueToken.getValuableTokenAmount());
}
/**@dev updates ValueToken holder state */
function updateHolder(address holder) internal {
// Update unprocessed deposits
if (lastBalance != address(this).balance) {
tokenPoints = totalTokenPoints();
lastBalance = address(this).balance;
}
//don't update balance for reserved tokens
if (!valueToken.reserved(holder)) {
// Claim share of deposits since last claim
bonusTokenPoints[holder] = bonusTokensToIssue(holder);
}
// Save dividend points for holder
if(lastClaimedPoints[holder] != tokenPoints) {
lastClaimedPoints[holder] = tokenPoints;
}
}
/**@dev issues an amount of bonus tokens that belongs to specific holder */
function issueBonusTokens(address holder) internal {
updateHolder(holder);
uint256 amount = bonusTokensToIssue(holder);
bonusTokenPoints[holder] = safeSub(bonusTokenPoints[holder], amount);
bonusToken.mint(holder, amount);
}
/**@dev transfers ether in exchange for bonus tokens */
function returnEther(address to, uint256 bonusTokensAmount) internal {
uint256 etherAmount = bonusTokensAmount / tokenEtherRate;
lastBalance = safeSub(lastBalance, etherAmount);
to.transfer(etherAmount);
}
} | *@dev how many tokens can be issued to specific account */ | function bonusTokensToIssue(address holder) public view returns (uint256) {
return safeAdd(bonusTokenPoints[holder], tokensSinceLastUpdate(holder));
}
| 1,078,075 | [
1,
13606,
4906,
2430,
848,
506,
16865,
358,
2923,
2236,
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
] | [
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,
324,
22889,
5157,
774,
12956,
12,
2867,
10438,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
4183,
986,
12,
18688,
407,
1345,
5636,
63,
4505,
6487,
2430,
9673,
3024,
1891,
12,
4505,
10019,
203,
565,
289,
7010,
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
] |
pragma solidity ^0.4.15;
import '../../installed_contracts/zeppelin-solidity/contracts/ownership/Ownable.sol';
/**
* @title Whitelist
* @dev The Whitelist contract has one or mutiple whitelist addresses, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*
* Created by IaM <DEV> (Elky Bachtiar)
* https://www.iamdeveloper.io
*
*
* file: Whitelist.sol
* location: ERC23/contracts/ownership/
*
*/
contract Whitelist is Ownable{
uint256 public maxAddresses = 5;
mapping (address => bool) public isWhitelisted;
address[] public whitelists;
event WhitelistRemoval(address indexed whitelist);
event WhitelistAddition(address indexed whitelist);
/**
* @dev The Whitelist constructor sets the whitlisted addresses of the contract to the sender
* account.
* @param _whitelists List of initial whitelisted addresses.
*/
function Whitelist(address[] _whitelists, uint256 _maxAddresses) {
for (uint256 i = 0; i < _whitelists.length; i++) {
require(!isWhitelisted[_whitelists[i]]);
require(_whitelists[i] != 0);
isWhitelisted[_whitelists[i]] = true;
}
whitelists = _whitelists;
maxAddresses = _maxAddresses;
}
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier addressWhitelisted(address _whitelist) {
assert(isWhitelisted[_whitelist]);
_;
}
modifier addressNotWhitelisted(address _whitelist) {
assert(!isWhitelisted[_whitelist]);
_;
}
/// @dev Returns Whitelists.
/// @return List of whitelist addresses.
function getWhitelists() public constant returns (address[]) {
return whitelists;
}
function checkWhitelisted(address _whitelist) public addressWhitelisted(_whitelist) returns (bool found){
return true;
}
function setMaxAddresses(uint256 _maxAddresses)
public
onlyOwner
returns (bool success)
{
require(_maxAddresses > 0);
maxAddresses = _maxAddresses;
return true;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param _whitelist Address of new whitelist address.
function addAddressToWhitelist(address _whitelist)
public
onlyOwner
addressNotWhitelisted(_whitelist)
returns (bool success)
{
require(_whitelist != 0);
isWhitelisted[_whitelist] = true;
whitelists.push(_whitelist);
WhitelistAddition(_whitelist);
return true;
}
/// @dev Allows to remove an address. Transaction has to be sent by wallet.
/// @param _whitelist Address of whitelisted list.
function removeAddressFromWhitelist(address _whitelist)
public
onlyOwner
//addressWhitelisted(_whitelist)
returns (bool success)
{
isWhitelisted[_whitelist] = false;
for (uint256 i = 0; i < whitelists.length - 1; i++) {
if (whitelists[i] == _whitelist) {
whitelists[i] = whitelists[whitelists.length - 1];
break;
}
whitelists.length -= 1;
WhitelistRemoval(_whitelist);
}
return true;
}
}
| @dev Allows to remove an address. Transaction has to be sent by wallet. @param _whitelist Address of whitelisted list.addressWhitelisted(_whitelist) | function removeAddressFromWhitelist(address _whitelist)
public
onlyOwner
returns (bool success)
{
isWhitelisted[_whitelist] = false;
for (uint256 i = 0; i < whitelists.length - 1; i++) {
if (whitelists[i] == _whitelist) {
whitelists[i] = whitelists[whitelists.length - 1];
break;
}
whitelists.length -= 1;
WhitelistRemoval(_whitelist);
}
return true;
}
| 5,387,179 | [
1,
19132,
358,
1206,
392,
1758,
18,
5947,
711,
358,
506,
3271,
635,
9230,
18,
225,
389,
20409,
5267,
434,
26944,
666,
18,
2867,
18927,
329,
24899,
20409,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
1887,
1265,
18927,
12,
2867,
389,
20409,
13,
7010,
3639,
1071,
203,
3639,
1338,
5541,
203,
3639,
1135,
261,
6430,
2216,
13,
203,
565,
288,
203,
3639,
353,
18927,
329,
63,
67,
20409,
65,
273,
629,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
600,
305,
292,
1486,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
309,
261,
3350,
305,
292,
1486,
63,
77,
65,
422,
389,
20409,
13,
288,
203,
7734,
600,
305,
292,
1486,
63,
77,
65,
273,
600,
305,
292,
1486,
63,
3350,
305,
292,
1486,
18,
2469,
300,
404,
15533,
203,
203,
7734,
898,
31,
203,
5411,
289,
203,
5411,
600,
305,
292,
1486,
18,
2469,
3947,
404,
31,
203,
5411,
3497,
7523,
24543,
24899,
20409,
1769,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x7e6706539e69349FFc73e25D9852196546de2D90/sources/A.sol | Have fun reading it. Hopefully it's bug-free. God bless. Info of each pool. | contract A is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
struct PoolInfo {
}
event Roll(address indexed user, uint256 indexed pid, uint256 amount, uint256 draw);
address public feeAddress;
PoolInfo[] public poolInfo;
constructor(address _feeAddress) public {
feeAddress = _feeAddress;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(
uint256 _maxWinChance,
IBEP20 _lpToken,
uint256 _depositFee,
uint256 _maxDepositAmount,
uint256 _winAmount
) public onlyOwner {
require(_depositFee <= 10000, 'add: invalid deposit fee');
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
maxWinChance: _maxWinChance,
maxDepositAmount: _maxDepositAmount,
depositFee: _depositFee,
winAmount: _winAmount
})
);
}
function add(
uint256 _maxWinChance,
IBEP20 _lpToken,
uint256 _depositFee,
uint256 _maxDepositAmount,
uint256 _winAmount
) public onlyOwner {
require(_depositFee <= 10000, 'add: invalid deposit fee');
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
maxWinChance: _maxWinChance,
maxDepositAmount: _maxDepositAmount,
depositFee: _depositFee,
winAmount: _winAmount
})
);
}
function move(uint256 _pid, address _moveAddress) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.lpToken.safeTransfer(_moveAddress, pool.lpToken.balanceOf(address(this)));
}
function set(
uint256 _pid,
uint256 _maxWinChance,
uint256 _maxDepositAmount,
uint256 _depositFee,
uint256 _winAmount
) public onlyOwner {
require(_depositFee <= 10000, 'set: invalid deposit fee');
require(_winAmount <= 10000, 'set: invalid win amount');
poolInfo[_pid].maxWinChance = _maxWinChance;
poolInfo[_pid].maxDepositAmount = _maxDepositAmount;
poolInfo[_pid].depositFee = _depositFee;
poolInfo[_pid].winAmount = _winAmount;
}
function _rand(uint256 max) internal returns (uint256) {
uint256 seed =
uint256(
keccak256(
abi.encodePacked(
block.timestamp +
block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) +
block.number
)
)
);
return (seed - ((seed / max) * max));
}
function roll(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 draw = 0;
if (_amount.div(pool.lpToken.balanceOf(address(this))).mul(10000) < pool.maxDepositAmount && _amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFee > 0) {
uint256 depositFee = _amount.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
}
draw = _rand(
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount).div(10000).mul(pool.maxWinChance)
);
if (_amount > draw) {
pool.lpToken.safeTransfer(
msg.sender,
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount)
);
}
emit Roll(msg.sender, _pid, _amount, draw);
emit Roll(msg.sender, _pid, 0, draw);
}
}
function roll(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 draw = 0;
if (_amount.div(pool.lpToken.balanceOf(address(this))).mul(10000) < pool.maxDepositAmount && _amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFee > 0) {
uint256 depositFee = _amount.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
}
draw = _rand(
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount).div(10000).mul(pool.maxWinChance)
);
if (_amount > draw) {
pool.lpToken.safeTransfer(
msg.sender,
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount)
);
}
emit Roll(msg.sender, _pid, _amount, draw);
emit Roll(msg.sender, _pid, 0, draw);
}
}
function roll(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 draw = 0;
if (_amount.div(pool.lpToken.balanceOf(address(this))).mul(10000) < pool.maxDepositAmount && _amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFee > 0) {
uint256 depositFee = _amount.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
}
draw = _rand(
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount).div(10000).mul(pool.maxWinChance)
);
if (_amount > draw) {
pool.lpToken.safeTransfer(
msg.sender,
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount)
);
}
emit Roll(msg.sender, _pid, _amount, draw);
emit Roll(msg.sender, _pid, 0, draw);
}
}
function roll(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 draw = 0;
if (_amount.div(pool.lpToken.balanceOf(address(this))).mul(10000) < pool.maxDepositAmount && _amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFee > 0) {
uint256 depositFee = _amount.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
}
draw = _rand(
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount).div(10000).mul(pool.maxWinChance)
);
if (_amount > draw) {
pool.lpToken.safeTransfer(
msg.sender,
pool.lpToken.balanceOf(address(this)).div(10000).mul(pool.winAmount)
);
}
emit Roll(msg.sender, _pid, _amount, draw);
emit Roll(msg.sender, _pid, 0, draw);
}
}
} else {
function setFeeAddress(address _feeAddress) public onlyOwner {
feeAddress = _feeAddress;
}
} | 11,374,038 | [
1,
17944,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
2845,
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
] | [
1,
1,
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,
16351,
432,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
5948,
52,
3462,
364,
467,
5948,
52,
3462,
31,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
203,
565,
871,
31291,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
2254,
5034,
3724,
1769,
203,
203,
565,
1758,
1071,
14036,
1887,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
3885,
12,
2867,
389,
21386,
1887,
13,
1071,
288,
203,
3639,
14036,
1887,
273,
389,
21386,
1887,
31,
203,
565,
289,
203,
203,
565,
445,
2845,
1782,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2845,
966,
18,
2469,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
203,
3639,
2254,
5034,
389,
1896,
18049,
782,
1359,
16,
203,
3639,
467,
5948,
52,
3462,
389,
9953,
1345,
16,
203,
3639,
2254,
5034,
389,
323,
1724,
14667,
16,
203,
3639,
2254,
5034,
389,
1896,
758,
1724,
6275,
16,
203,
3639,
2254,
5034,
389,
8082,
6275,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
323,
1724,
14667,
1648,
12619,
16,
296,
1289,
30,
2057,
443,
1724,
14036,
8284,
203,
3639,
2845,
966,
18,
6206,
12,
203,
5411,
8828,
966,
12590,
203,
7734,
12423,
1345,
30,
389,
9953,
1345,
16,
203,
7734,
943,
18049,
782,
1359,
30,
389,
1896,
18049,
782,
1359,
16,
203,
7734,
943,
758,
1724,
6275,
30,
389,
1896,
758,
1724,
6275,
16,
203,
2
] |
./partial_match/1/0x1E70FDe6dEc595d0c9897f0296409A6dc5457560/sources/Staking.sol | tranfers the token back to the user from the contract | function unstake(uint256[]calldata tokenIds, uint256[]calldata collectionIdx) external {
require(tokenIds.length == collectionIdx.length, "Array lengths must match");
for(uint256 i = 0; i < tokenIds.length; i++){
require(_owners[tokenIds[i]] == msg.sender, "Trying to unstake unowned token");
IERC721(collectionAddresses[collectionIdx[i]]).transferFrom(address(this), msg.sender, tokenIds[i]);
_removeTokenFromOwnerEnumeration(msg.sender, tokenIds[i]);
_owners[tokenIds[i]] = address(0);
}
rewardToken.calculateNewReward(msg.sender);
}
| 3,947,472 | [
1,
13171,
18881,
326,
1147,
1473,
358,
326,
729,
628,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
640,
334,
911,
12,
11890,
5034,
8526,
1991,
892,
1147,
2673,
16,
2254,
5034,
8526,
1991,
892,
1849,
4223,
13,
3903,
288,
203,
3639,
2583,
12,
2316,
2673,
18,
2469,
422,
1849,
4223,
18,
2469,
16,
315,
1076,
10917,
1297,
845,
8863,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
1147,
2673,
18,
2469,
31,
277,
27245,
95,
203,
5411,
2583,
24899,
995,
414,
63,
2316,
2673,
63,
77,
13563,
422,
1234,
18,
15330,
16,
315,
18038,
358,
640,
334,
911,
640,
995,
329,
1147,
8863,
203,
5411,
467,
654,
39,
27,
5340,
12,
5548,
7148,
63,
5548,
4223,
63,
77,
13563,
2934,
13866,
1265,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
1147,
2673,
63,
77,
19226,
203,
5411,
389,
4479,
1345,
1265,
5541,
21847,
12,
3576,
18,
15330,
16,
1147,
2673,
63,
77,
19226,
203,
5411,
389,
995,
414,
63,
2316,
2673,
63,
77,
13563,
273,
1758,
12,
20,
1769,
203,
3639,
289,
203,
3639,
19890,
1345,
18,
11162,
1908,
17631,
1060,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xfA22740d9A87e7d8c37C2D271A48Ce4def2d121E/sources/contracts/AliensNFT.sol | Get the price of the token Id | function priceOf(uint256 tokenId) public view returns (uint256) {
uint256 price = _prices[tokenId];
require(price != 0, "Aliens NFT: invalid token ID");
return price;
}
| 9,752,842 | [
1,
967,
326,
6205,
434,
326,
1147,
3124,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6205,
951,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
6205,
273,
389,
683,
1242,
63,
2316,
548,
15533,
203,
203,
3639,
2583,
12,
8694,
480,
374,
16,
315,
37,
549,
773,
423,
4464,
30,
2057,
1147,
1599,
8863,
203,
203,
3639,
327,
6205,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import {IWETH9} from "../interfaces/IWETH9.sol";
import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol";
import {IShortPowerPerp} from "../interfaces/IShortPowerPerp.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {VaultLib} from "../libs/VaultLib.sol";
import {Uint256Casting} from "../libs/Uint256Casting.sol";
import {Power2Base} from "../libs/Power2Base.sol";
/**
*
* Error
* C0: Paused
* C1: Not paused
* C2: Shutdown
* C3: Not shutdown
* C4: Invalid oracle address
* C5: Invalid shortPowerPerp address
* C6: Invalid wPowerPerp address
* C7: Invalid weth address
* C8: Invalid quote currency address
* C9: Invalid eth:quoteCurrency pool address
* C10: Invalid wPowerPerp:eth pool address
* C11: Invalid Uniswap position manager
* C12: Can not liquidate safe vault
* C13: Invalid address
* C14: Set fee recipient first
* C15: Fee too high
* C16: Paused too many times
* C17: Pause time limit exceeded
* C18: Not enough paused time has passed
* C19: Cannot receive eth
* C20: Invalid vault id
* C21: Need full liquidation
* C22: Dust vault left
* C23: Invalid nft
* C24: Invalid state
* C25: Not allowed
*/
contract Controller is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using Uint256Casting for uint256;
using VaultLib for VaultLib.Vault;
using Address for address payable;
uint256 internal constant MIN_COLLATERAL = 0.5 ether;
/// @dev system can only be paused for 182 days from deployment
uint256 internal constant PAUSE_TIME_LIMIT = 182 days;
uint256 internal constant FUNDING_PERIOD = 1 days;
uint32 public constant TWAP_PERIOD = 5 minutes;
//80% of index
uint256 internal constant LOWER_MARK_RATIO = 8e17;
//125% of index
uint256 internal constant UPPER_MARK_RATIO = 125e16;
// 10%
uint256 internal constant LIQUIDATION_BOUNTY = 1e17;
// 2%
uint256 internal constant REDUCE_DEBT_BOUNTY = 2e16;
/// @dev basic unit used for calculation
uint256 private constant ONE = 1e18;
uint256 private constant ONE_ONE = 1e36;
address public immutable weth;
address public immutable quoteCurrency;
address public immutable ethQuoteCurrencyPool;
/// @dev address of the powerPerp/weth pool
address public immutable wPowerPerpPool;
address internal immutable uniswapPositionManager;
address public immutable shortPowerPerp;
address public immutable wPowerPerp;
address public immutable oracle;
address public feeRecipient;
uint256 internal immutable deployTimestamp;
/// @dev fee rate in basis point. feeRate of 1 = 0.01%
uint256 public feeRate;
/// @dev the settlement price for each wPowerPerp for settlement
uint256 public indexForSettlement;
uint256 public pausesLeft = 4;
uint256 public lastPauseTime;
// these 2 parameters are always updated together. Use uint128 to batch read and write.
uint128 public normalizationFactor;
uint128 public lastFundingUpdateTimestamp;
bool internal immutable isWethToken0;
bool public isShutDown;
bool public isSystemPaused;
/// @dev vault data storage
mapping(uint256 => VaultLib.Vault) public vaults;
/// Events
event OpenVault(address sender, uint256 vaultId);
event DepositCollateral(address sender, uint256 vaultId, uint256 amount);
event DepositUniPositionToken(address sender, uint256 vaultId, uint256 tokenId);
event WithdrawCollateral(address sender, uint256 vaultId, uint256 amount);
event WithdrawUniPositionToken(address sender, uint256 vaultId, uint256 tokenId);
event MintShort(address sender, uint256 amount, uint256 vaultId);
event BurnShort(address sender, uint256 amount, uint256 vaultId);
event ReduceDebt(
address sender,
uint256 vaultId,
uint256 ethRedeemed,
uint256 wPowerPerpRedeemed,
uint256 wPowerPerpBurned,
uint256 wPowerPerpExcess,
uint256 bounty
);
event UpdateOperator(address sender, uint256 vaultId, address operator);
event FeeRateUpdated(uint256 oldFee, uint256 newFee);
event FeeRecipientUpdated(address oldFeeRecipient, address newFeeRecipient);
event Liquidate(address liquidator, uint256 vaultId, uint256 debtAmount, uint256 collateralPaid);
event NormalizationFactorUpdated(
uint256 oldNormFactor,
uint256 newNormFactor,
uint256 lastModificationTimestamp,
uint256 timestamp
);
event Paused(uint256 pausesLeft);
event UnPaused(address unpauser);
event Shutdown(uint256 indexForSettlement);
event RedeemLong(address sender, uint256 wPowerPerpAmount, uint256 payoutAmount);
event RedeemShort(address sender, uint256 vauldId, uint256 collateralAmount);
modifier notPaused() {
require(!isSystemPaused, "C0");
_;
}
modifier isPaused() {
require(isSystemPaused, "C1");
_;
}
modifier notShutdown() {
require(!isShutDown, "C2");
_;
}
modifier isShutdown() {
require(isShutDown, "C3");
_;
}
/**
* @notice constructor
* @param _oracle oracle address
* @param _shortPowerPerp ERC721 token address representing the short position
* @param _wPowerPerp ERC20 token address representing the long position
* @param _weth weth address
* @param _quoteCurrency quoteCurrency address
* @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency
* @param _wPowerPerpPool uniswap v3 pool for wPowerPerp / weth
* @param _uniPositionManager uniswap v3 position manager address
*/
constructor(
address _oracle,
address _shortPowerPerp,
address _wPowerPerp,
address _weth,
address _quoteCurrency,
address _ethQuoteCurrencyPool,
address _wPowerPerpPool,
address _uniPositionManager
) {
require(_oracle != address(0), "C4");
require(_shortPowerPerp != address(0), "C5");
require(_wPowerPerp != address(0), "C6");
require(_weth != address(0), "C7");
require(_quoteCurrency != address(0), "C8");
require(_ethQuoteCurrencyPool != address(0), "C9");
require(_wPowerPerpPool != address(0), "C10");
require(_uniPositionManager != address(0), "C11");
oracle = _oracle;
shortPowerPerp = _shortPowerPerp;
wPowerPerp = _wPowerPerp;
weth = _weth;
quoteCurrency = _quoteCurrency;
ethQuoteCurrencyPool = _ethQuoteCurrencyPool;
wPowerPerpPool = _wPowerPerpPool;
uniswapPositionManager = _uniPositionManager;
isWethToken0 = _weth < _wPowerPerp;
normalizationFactor = 1e18;
deployTimestamp = block.timestamp;
lastFundingUpdateTimestamp = block.timestamp.toUint128();
}
/**
* ======================
* | External Functions |
* ======================
*/
/**
* @notice returns the expected normalization factor, if the funding is paid right now
* @dev can be used for on-chain and off-chain calculations
*/
function getExpectedNormalizationFactor() external view returns (uint256) {
return _getNewNormalizationFactor();
}
/**
* @notice get the index price of the powerPerp, scaled down
* @dev the index price is scaled down by INDEX_SCALE in the associated PowerXBase library
* @dev this is the index price used when calculating funding and for collateralization
* @param _period period which you want to calculate twap with
* @return index price denominated in $USD, scaled by 1e18
*/
function getIndex(uint32 _period) external view returns (uint256) {
return Power2Base._getIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency);
}
/**
* @notice the unscaled index of the power perp in USD, scaled by 18 decimals
* @dev this is the mark that would be be used for future funding after a new normalization factor is applied
* @param _period period which you want to calculate twap with
* @return index price denominated in $USD, scaled by 1e18
*/
function getUnscaledIndex(uint32 _period) external view returns (uint256) {
return Power2Base._getUnscaledIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency);
}
/**
* @notice get the expected mark price of powerPerp after funding has been applied
* @param _period period of time for the twap in seconds
* @return mark price denominated in $USD, scaled by 1e18
*/
function getDenormalizedMark(uint32 _period) external view returns (uint256) {
return
Power2Base._getDenormalizedMark(
_period,
oracle,
wPowerPerpPool,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
wPowerPerp,
_getNewNormalizationFactor()
);
}
/**
* @notice get the mark price of powerPerp before funding has been applied
* @dev this is the mark that would be used to calculate a new normalization factor if funding was calculated now
* @param _period period which you want to calculate twap with
* @return mark price denominated in $USD, scaled by 1e18
*/
function getDenormalizedMarkForFunding(uint32 _period) external view returns (uint256) {
return
Power2Base._getDenormalizedMark(
_period,
oracle,
wPowerPerpPool,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
wPowerPerp,
normalizationFactor
);
}
/**
* @dev return if the vault is properly collateralized
* @param _vaultId id of the vault
* @return true if the vault is properly collateralized
*/
function isVaultSafe(uint256 _vaultId) external view returns (bool) {
VaultLib.Vault memory vault = vaults[_vaultId];
uint256 expectedNormalizationFactor = _getNewNormalizationFactor();
return _isVaultSafe(vault, expectedNormalizationFactor);
}
/**
* @notice deposit collateral and mint wPowerPerp (non-rebasing) for specified powerPerp (rebasing) amount
* @param _vaultId vault to mint wPowerPerp in
* @param _powerPerpAmount amount of powerPerp to mint
* @param _uniTokenId uniswap v3 position token id (additional collateral)
* @return vaultId
* @return amount of wPowerPerp minted
*/
function mintPowerPerpAmount(
uint256 _vaultId,
uint256 _powerPerpAmount,
uint256 _uniTokenId
) external payable notPaused nonReentrant returns (uint256, uint256) {
return _openDepositMint(msg.sender, _vaultId, _powerPerpAmount, msg.value, _uniTokenId, false);
}
/**
* @notice deposit collateral and mint wPowerPerp
* @param _vaultId vault to mint wPowerPerp in
* @param _wPowerPerpAmount amount of wPowerPerp to mint
* @param _uniTokenId uniswap v3 position token id (additional collateral)
* @return vaultId
*/
function mintWPowerPerpAmount(
uint256 _vaultId,
uint256 _wPowerPerpAmount,
uint256 _uniTokenId
) external payable notPaused nonReentrant returns (uint256) {
(uint256 vaultId, ) = _openDepositMint(msg.sender, _vaultId, _wPowerPerpAmount, msg.value, _uniTokenId, true);
return vaultId;
}
/**
* @dev deposit collateral into a vault
* @param _vaultId id of the vault
*/
function deposit(uint256 _vaultId) external payable notPaused nonReentrant {
_checkVaultId(_vaultId);
_applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_addEthCollateral(cachedVault, _vaultId, msg.value);
_writeVault(_vaultId, cachedVault);
}
/**
* @notice deposit uniswap position token into a vault to increase collateral ratio
* @param _vaultId id of the vault
* @param _uniTokenId uniswap position token id
*/
function depositUniPositionToken(uint256 _vaultId, uint256 _uniTokenId) external notPaused nonReentrant {
_checkVaultId(_vaultId);
_applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_depositUniPositionToken(cachedVault, msg.sender, _vaultId, _uniTokenId);
_writeVault(_vaultId, cachedVault);
}
/**
* @notice withdraw collateral from a vault
* @param _vaultId id of the vault
* @param _amount amount of eth to withdraw
*/
function withdraw(uint256 _vaultId, uint256 _amount) external notPaused nonReentrant {
uint256 cachedNormFactor = _applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_withdrawCollateral(cachedVault, msg.sender, _vaultId, _amount);
_checkVault(cachedVault, cachedNormFactor);
_writeVault(_vaultId, cachedVault);
payable(msg.sender).sendValue(_amount);
}
/**
* @notice withdraw uniswap v3 position token from a vault
* @param _vaultId id of the vault
*/
function withdrawUniPositionToken(uint256 _vaultId) external notPaused nonReentrant {
uint256 cachedNormFactor = _applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_withdrawUniPositionToken(cachedVault, msg.sender, _vaultId);
_checkVault(cachedVault, cachedNormFactor);
_writeVault(_vaultId, cachedVault);
}
/**
* @notice burn wPowerPerp and remove collateral from a vault
* @param _vaultId id of the vault
* @param _wPowerPerpAmount amount of wPowerPerp to burn
* @param _withdrawAmount amount of eth to withdraw
*/
function burnWPowerPerpAmount(
uint256 _vaultId,
uint256 _wPowerPerpAmount,
uint256 _withdrawAmount
) external notPaused nonReentrant {
_burnAndWithdraw(msg.sender, _vaultId, _wPowerPerpAmount, _withdrawAmount, true);
}
/**
* @notice burn powerPerp and remove collateral from a vault
* @param _vaultId id of the vault
* @param _powerPerpAmount amount of powerPerp to burn
* @param _withdrawAmount amount of eth to withdraw
* @return amount of wPowerPerp burned
*/
function burnPowerPerpAmount(
uint256 _vaultId,
uint256 _powerPerpAmount,
uint256 _withdrawAmount
) external notPaused nonReentrant returns (uint256) {
return _burnAndWithdraw(msg.sender, _vaultId, _powerPerpAmount, _withdrawAmount, false);
}
/**
* @notice after the system is shutdown, insolvent vaults need to be have their uniswap v3 token assets withdrawn by force
* @notice if a vault has a uniswap v3 position in it, anyone can call to withdraw uniswap v3 token assets, reducing debt and increasing collateral in the vault
* @dev the caller won't get any bounty. this is expected to be used for insolvent vaults in shutdown
* @param _vaultId vault containing uniswap v3 position to liquidate
*/
function reduceDebtShutdown(uint256 _vaultId) external isShutdown nonReentrant {
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_reduceDebt(
cachedVault,
IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId),
_vaultId,
normalizationFactor,
false
);
_writeVault(_vaultId, cachedVault);
}
/**
* @notice withdraw assets from uniswap v3 position, reducing debt and increasing collateral in the vault
* @dev the caller won't get any bounty. this is expected to be used by vault owner
* @param _vaultId target vault
*/
function reduceDebt(uint256 _vaultId) external notPaused nonReentrant {
_checkCanModifyVault(_vaultId, msg.sender);
uint256 cachedNormFactor = _applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_reduceDebt(cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, cachedNormFactor, false);
_writeVault(_vaultId, cachedVault);
}
/**
* @notice if a vault is under the 150% collateral ratio, anyone can liquidate the vault by burning wPowerPerp
* @dev liquidator can get back (wPowerPerp burned) * (index price) * (normalizationFactor) * 110% in collateral
* @dev normally can only liquidate 50% of a vault's debt
* @dev if a vault is under dust limit after a liquidation can fully liquidate
* @dev will attempt to reduceDebt first, and can earn a bounty if sucessful
* @param _vaultId vault to liquidate
* @param _maxDebtAmount max amount of wPowerPerpetual to repay
* @return amount of wPowerPerp repaid
*/
function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external notPaused nonReentrant returns (uint256) {
_checkVaultId(_vaultId);
uint256 cachedNormFactor = _applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
require(!_isVaultSafe(cachedVault, cachedNormFactor), "C12");
// try to save target vault before liquidation by reducing debt
uint256 bounty = _reduceDebt(
cachedVault,
IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId),
_vaultId,
cachedNormFactor,
true
);
// if vault is safe after saving, pay bounty and return early
if (_isVaultSafe(cachedVault, cachedNormFactor)) {
_writeVault(_vaultId, cachedVault);
payable(msg.sender).sendValue(bounty);
return 0;
}
// add back the bounty amount, liquidators onlly get reward from liquidation
cachedVault.addEthCollateral(bounty);
// if the vault is still not safe after saving, liquidate it
(uint256 debtAmount, uint256 collateralPaid) = _liquidate(
cachedVault,
_maxDebtAmount,
cachedNormFactor,
msg.sender
);
emit Liquidate(msg.sender, _vaultId, debtAmount, collateralPaid);
_writeVault(_vaultId, cachedVault);
// pay the liquidator
payable(msg.sender).sendValue(collateralPaid);
return debtAmount;
}
/**
* @notice authorize an address to modify the vault
* @dev can be revoke by setting address to 0
* @param _vaultId id of the vault
* @param _operator new operator address
*/
function updateOperator(uint256 _vaultId, address _operator) external {
require(IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == msg.sender, "C25");
vaults[_vaultId].operator = _operator;
emit UpdateOperator(msg.sender, _vaultId, _operator);
}
/**
* @notice set the recipient who will receive the fee
* @dev this should be a contract handling insurance
* @param _newFeeRecipient new fee recipient
*/
function setFeeRecipient(address _newFeeRecipient) external onlyOwner {
require(_newFeeRecipient != address(0), "C13");
emit FeeRecipientUpdated(feeRecipient, _newFeeRecipient);
feeRecipient = _newFeeRecipient;
}
/**
* @notice set the fee rate when user mints
* @dev this function cannot be called if the feeRecipient is still un-set
* @param _newFeeRate new fee rate in basis points. can't be higher than 1%
*/
function setFeeRate(uint256 _newFeeRate) external onlyOwner {
require(feeRecipient != address(0), "C14");
require(_newFeeRate <= 100, "C15");
emit FeeRateUpdated(feeRate, _newFeeRate);
feeRate = _newFeeRate;
}
/**
* @notice pause (if not paused) and then immediately shutdown the system, can be called when paused already
* @dev this bypasses the check on number of pauses or time based checks, but is irreversible and enables emergency settlement
*/
function shutDown() external onlyOwner notShutdown {
isSystemPaused = true;
isShutDown = true;
indexForSettlement = Power2Base._getScaledTwap(
oracle,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
TWAP_PERIOD,
false
);
}
/**
* @notice pause the system for up to 24 hours after which any one can unpause
* @dev can only be called for 365 days since the contract was launched or 4 times
*/
function pause() external onlyOwner notShutdown notPaused {
require(pausesLeft > 0, "C16");
uint256 timeSinceDeploy = block.timestamp.sub(deployTimestamp);
require(timeSinceDeploy < PAUSE_TIME_LIMIT, "C17");
isSystemPaused = true;
pausesLeft -= 1;
lastPauseTime = block.timestamp;
emit Paused(pausesLeft);
}
/**
* @notice unpause the contract
* @dev anyone can unpause the contract after 24 hours
*/
function unPauseAnyone() external isPaused notShutdown {
require(block.timestamp > (lastPauseTime + 1 days), "C18");
isSystemPaused = false;
emit UnPaused(msg.sender);
}
/**
* @notice unpause the contract
* @dev owner can unpause at any time
*/
function unPauseOwner() external onlyOwner isPaused notShutdown {
isSystemPaused = false;
emit UnPaused(msg.sender);
}
/**
* @notice redeem wPowerPerp for (settlement index value) * normalizationFactor when the system is shutdown
* @param _wPerpAmount amount of wPowerPerp to burn
*/
function redeemLong(uint256 _wPerpAmount) external isShutdown nonReentrant {
IWPowerPerp(wPowerPerp).burn(msg.sender, _wPerpAmount);
uint256 longValue = Power2Base._getLongSettlementValue(_wPerpAmount, indexForSettlement, normalizationFactor);
payable(msg.sender).sendValue(longValue);
emit RedeemLong(msg.sender, _wPerpAmount, longValue);
}
/**
* @notice redeem short position when the system is shutdown
* @dev short position is redeemed by valuing the debt at the (settlement index value) * normalizationFactor
* @param _vaultId vault id
*/
function redeemShort(uint256 _vaultId) external isShutdown nonReentrant {
_checkCanModifyVault(_vaultId, msg.sender);
VaultLib.Vault memory cachedVault = vaults[_vaultId];
uint256 cachedNormFactor = normalizationFactor;
_reduceDebt(cachedVault, msg.sender, _vaultId, cachedNormFactor, false);
uint256 debt = Power2Base._getLongSettlementValue(
cachedVault.shortAmount,
indexForSettlement,
cachedNormFactor
);
// if the debt is more than collateral, this line will revert
uint256 excess = uint256(cachedVault.collateralAmount).sub(debt);
// reset the vault but don't burn the nft, just because people may want to keep it
cachedVault.shortAmount = 0;
cachedVault.collateralAmount = 0;
_writeVault(_vaultId, cachedVault);
payable(msg.sender).sendValue(excess);
emit RedeemShort(msg.sender, _vaultId, excess);
}
/**
* @notice update the normalization factor as a way to pay funding
*/
function applyFunding() external notPaused {
_applyFunding();
}
/**
* @notice add eth into a contract. used in case contract has insufficient eth to pay for settlement transactions
*/
function donate() external payable isShutdown {}
/**
* @notice fallback function to accept eth
*/
receive() external payable {
require(msg.sender == weth, "C19");
}
/*
* ======================
* | Internal Functions |
* ======================
*/
/**
* @notice check if a vaultId is valid, reverts if it's not valid
* @param _vaultId the id to check
*/
function _checkVaultId(uint256 _vaultId) internal view {
require(_vaultId > 0 && _vaultId < IShortPowerPerp(shortPowerPerp).nextId(), "C20");
}
/**
* @notice check if an address can modify a vault
* @param _vaultId the id of the vault to check if can be modified by _account
* @param _account the address to check if can modify the vault
*/
function _checkCanModifyVault(uint256 _vaultId, address _account) internal view {
require(
IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == _account || vaults[_vaultId].operator == _account,
"C25"
);
}
/**
* @notice wrapper function which open a vault, add collateral and mint wPowerPerp
* @param _account account to receive wPowerPerp
* @param _vaultId id of the vault
* @param _mintAmount amount to mint
* @param _depositAmount amount of eth as collateral
* @param _uniTokenId id of uniswap v3 position token
* @param _isWAmount if the input amount is wPowerPerp (as opposed to rebasing powerPerp)
* @return vaultId
* @return total minted wPowerPower amount
*/
function _openDepositMint(
address _account,
uint256 _vaultId,
uint256 _mintAmount,
uint256 _depositAmount,
uint256 _uniTokenId,
bool _isWAmount
) internal returns (uint256, uint256) {
uint256 cachedNormFactor = _applyFunding();
uint256 depositAmountWithFee = _depositAmount;
uint256 wPowerPerpAmount = _isWAmount ? _mintAmount : _mintAmount.mul(ONE).div(cachedNormFactor);
uint256 feeAmount;
VaultLib.Vault memory cachedVault;
// load vault or create new a new one
if (_vaultId == 0) {
(_vaultId, cachedVault) = _openVault(_account);
} else {
// make sure we're not accessing an unexistent vault.
_checkVaultId(_vaultId);
cachedVault = vaults[_vaultId];
}
if (wPowerPerpAmount > 0) {
(feeAmount, depositAmountWithFee) = _getFee(
cachedVault,
wPowerPerpAmount,
_depositAmount,
cachedNormFactor
);
_mintWPowerPerp(cachedVault, _account, _vaultId, wPowerPerpAmount);
}
if (_depositAmount > 0) _addEthCollateral(cachedVault, _vaultId, depositAmountWithFee);
if (_uniTokenId != 0) _depositUniPositionToken(cachedVault, _account, _vaultId, _uniTokenId);
_checkVault(cachedVault, cachedNormFactor);
_writeVault(_vaultId, cachedVault);
// pay insurance fee
if (feeAmount > 0) payable(feeRecipient).sendValue(feeAmount);
return (_vaultId, wPowerPerpAmount);
}
/**
* @notice wrapper function to burn wPowerPerp and redeem collateral
* @param _account who should receive collateral
* @param _vaultId id of the vault
* @param _burnAmount amount of wPowerPerp to burn
* @param _withdrawAmount amount of eth collateral to withdraw
* @param _isWAmount true if the amount is wPowerPerp (as opposed to rebasing powerPerp)
* @return total burned wPowerPower amount
*/
function _burnAndWithdraw(
address _account,
uint256 _vaultId,
uint256 _burnAmount,
uint256 _withdrawAmount,
bool _isWAmount
) internal returns (uint256) {
_checkVaultId(_vaultId);
uint256 cachedNormFactor = _applyFunding();
uint256 wBurnAmount = _isWAmount ? _burnAmount : _burnAmount.mul(ONE).div(cachedNormFactor);
VaultLib.Vault memory cachedVault = vaults[_vaultId];
if (wBurnAmount > 0) _burnWPowerPerp(cachedVault, _account, _vaultId, wBurnAmount);
if (_withdrawAmount > 0) _withdrawCollateral(cachedVault, _account, _vaultId, _withdrawAmount);
_checkVault(cachedVault, cachedNormFactor);
_writeVault(_vaultId, cachedVault);
if (_withdrawAmount > 0) payable(msg.sender).sendValue(_withdrawAmount);
return wBurnAmount;
}
/**
* @notice open a new vault
* @dev create a new vault and bind it with a new short vault id
* @param _recipient owner of new vault
* @return id of the new vault
* @return new in-memory vault
*/
function _openVault(address _recipient) internal returns (uint256, VaultLib.Vault memory) {
uint256 vaultId = IShortPowerPerp(shortPowerPerp).mintNFT(_recipient);
VaultLib.Vault memory vault = VaultLib.Vault({
NftCollateralId: 0,
collateralAmount: 0,
shortAmount: 0,
operator: address(0)
});
emit OpenVault(msg.sender, vaultId);
return (vaultId, vault);
}
/**
* @notice deposit uniswap v3 position token into a vault
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _account account to transfer the uniswap v3 position from
* @param _vaultId id of the vault
* @param _uniTokenId uniswap position token id
*/
function _depositUniPositionToken(
VaultLib.Vault memory _vault,
address _account,
uint256 _vaultId,
uint256 _uniTokenId
) internal {
//get tokens for uniswap NFT
(, , address token0, address token1, , , , , , , , ) = INonfungiblePositionManager(uniswapPositionManager)
.positions(_uniTokenId);
// only check token0 and token1, ignore fee
// if there are multiple wPowerPerp/weth pools with different fee rate, accept position tokens from any of them
require((token0 == wPowerPerp && token1 == weth) || (token1 == wPowerPerp && token0 == weth), "C23");
_vault.addUniNftCollateral(_uniTokenId);
INonfungiblePositionManager(uniswapPositionManager).transferFrom(_account, address(this), _uniTokenId);
emit DepositUniPositionToken(msg.sender, _vaultId, _uniTokenId);
}
/**
* @notice add eth collateral into a vault
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update.
* @param _amount amount of eth adding to the vault
*/
function _addEthCollateral(
VaultLib.Vault memory _vault,
uint256 _vaultId,
uint256 _amount
) internal {
_vault.addEthCollateral(_amount);
emit DepositCollateral(msg.sender, _vaultId, _amount);
}
/**
* @notice remove uniswap v3 position token from the vault
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _account where to send the uni position token to
* @param _vaultId id of the vault
*/
function _withdrawUniPositionToken(
VaultLib.Vault memory _vault,
address _account,
uint256 _vaultId
) internal {
_checkCanModifyVault(_vaultId, _account);
uint256 tokenId = _vault.NftCollateralId;
_vault.removeUniNftCollateral();
INonfungiblePositionManager(uniswapPositionManager).transferFrom(address(this), _account, tokenId);
emit WithdrawUniPositionToken(msg.sender, _vaultId, tokenId);
}
/**
* @notice remove eth collateral from the vault
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _account where to send collateral to
* @param _vaultId id of the vault
* @param _amount amount of eth to withdraw
*/
function _withdrawCollateral(
VaultLib.Vault memory _vault,
address _account,
uint256 _vaultId,
uint256 _amount
) internal {
_checkCanModifyVault(_vaultId, _account);
_vault.removeEthCollateral(_amount);
emit WithdrawCollateral(msg.sender, _vaultId, _amount);
}
/**
* @notice mint wPowerPerp (ERC20) to an account
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _account account to receive wPowerPerp
* @param _vaultId id of the vault
* @param _wPowerPerpAmount wPowerPerp amount to mint
*/
function _mintWPowerPerp(
VaultLib.Vault memory _vault,
address _account,
uint256 _vaultId,
uint256 _wPowerPerpAmount
) internal {
_checkCanModifyVault(_vaultId, _account);
_vault.addShort(_wPowerPerpAmount);
IWPowerPerp(wPowerPerp).mint(_account, _wPowerPerpAmount);
emit MintShort(msg.sender, _wPowerPerpAmount, _vaultId);
}
/**
* @notice burn wPowerPerp (ERC20) from an account
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _account account burning the wPowerPerp
* @param _vaultId id of the vault
* @param _wPowerPerpAmount wPowerPerp amount to burn
*/
function _burnWPowerPerp(
VaultLib.Vault memory _vault,
address _account,
uint256 _vaultId,
uint256 _wPowerPerpAmount
) internal {
_vault.removeShort(_wPowerPerpAmount);
IWPowerPerp(wPowerPerp).burn(_account, _wPowerPerpAmount);
emit BurnShort(msg.sender, _wPowerPerpAmount, _vaultId);
}
/**
* @notice liquidate a vault, pay the liquidator
* @dev liquidator can only liquidate at most 1/2 of the vault in 1 transaction
* @dev this function will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _maxWPowerPerpAmount maximum debt amount liquidator is willing to repay
* @param _normalizationFactor current normalization factor
* @param _liquidator liquidator address to receive eth
* @return debtAmount amount of wPowerPerp repaid (burn from the vault)
* @return collateralToPay amount of collateral paid to liquidator
*/
function _liquidate(
VaultLib.Vault memory _vault,
uint256 _maxWPowerPerpAmount,
uint256 _normalizationFactor,
address _liquidator
) internal returns (uint256, uint256) {
(uint256 liquidateAmount, uint256 collateralToPay) = _getLiquidationResult(
_maxWPowerPerpAmount,
uint256(_vault.shortAmount),
uint256(_vault.collateralAmount),
_normalizationFactor
);
// if the liquidator didn't specify enough wPowerPerp to burn, revert.
require(_maxWPowerPerpAmount >= liquidateAmount, "C21");
IWPowerPerp(wPowerPerp).burn(_liquidator, liquidateAmount);
_vault.removeShort(liquidateAmount);
_vault.removeEthCollateral(collateralToPay);
(, bool isDust) = _getVaultStatus(_vault, _normalizationFactor);
require(!isDust, "C22");
return (liquidateAmount, collateralToPay);
}
/**
* @notice redeem uniswap v3 position in a vault for its constituent eth and wSqueeth
* @notice this will increase vault collateral by the amount of eth, and decrease debt by the amount of wSqueeth
* @dev will be executed before liquidation if there's an NFT in the vault
* @dev pays a 2% bounty to the liquidator if called by liquidate()
* @dev will update the vault memory in-place
* @param _vault the Vault memory to update
* @param _owner account to send any excess
* @param _payBounty true if paying caller 2% bounty
* @return bounty amount of bounty paid for liquidator
*/
function _reduceDebt(
VaultLib.Vault memory _vault,
address _owner,
uint256 _vaultId,
uint256 _normalizationFactor,
bool _payBounty
) internal returns (uint256) {
uint256 nftId = _vault.NftCollateralId;
if (nftId == 0) return 0;
(uint256 withdrawnEthAmount, uint256 withdrawnWPowerPerpAmount) = _redeemUniToken(nftId);
// change weth back to eth
if (withdrawnEthAmount > 0) IWETH9(weth).withdraw(withdrawnEthAmount);
(uint256 burnAmount, uint256 excess, uint256 bounty) = _getReduceDebtResultInVault(
_vault,
withdrawnEthAmount,
withdrawnWPowerPerpAmount,
_normalizationFactor,
_payBounty
);
if (excess > 0) IWPowerPerp(wPowerPerp).transfer(_owner, excess);
if (burnAmount > 0) IWPowerPerp(wPowerPerp).burn(address(this), burnAmount);
emit ReduceDebt(
msg.sender,
_vaultId,
withdrawnEthAmount,
withdrawnWPowerPerpAmount,
burnAmount,
excess,
bounty
);
return bounty;
}
/**
* @notice pay fee recipient
* @dev pay in eth from either the vault or the deposit amount
* @param _vault the Vault memory to update
* @param _wSqueethAmount the amount of wSqueeth minting
* @param _depositAmount the amount of eth depositing or withdrawing
* @param _normalizationFactor current normalization factor
* @return the amount of actual deposited eth into the vault, this is less than the original amount if a fee was taken
*/
function _getFee(
VaultLib.Vault memory _vault,
uint256 _wSqueethAmount,
uint256 _depositAmount,
uint256 _normalizationFactor
) internal view returns (uint256, uint256) {
uint256 cachedFeeRate = feeRate;
if (cachedFeeRate == 0) return (uint256(0), _depositAmount);
uint256 depositAmountAfterFee;
uint256 ethEquivalentMinted = Power2Base._getDebtValueInEth(
_wSqueethAmount,
oracle,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
_normalizationFactor
);
uint256 feeAmount = ethEquivalentMinted.mul(cachedFeeRate).div(10000);
// if fee can be paid from deposited collateral, pay from _depositAmount
if (_depositAmount > feeAmount) {
depositAmountAfterFee = _depositAmount.sub(feeAmount);
// if not, adjust the vault to pay from the vault collateral
} else {
_vault.removeEthCollateral(feeAmount);
depositAmountAfterFee = _depositAmount;
}
//return the fee and deposit amount, which has only been reduced by a fee if it is paid out of the deposit amount
return (feeAmount, depositAmountAfterFee);
}
/**
* @notice write vault to storage
* @dev writes to vaults mapping
*/
function _writeVault(uint256 _vaultId, VaultLib.Vault memory _vault) private {
vaults[_vaultId] = _vault;
}
/**
* @dev redeem a uni position token and get back wPowerPerp and eth
* @param _uniTokenId uniswap v3 position token id
* @return wethAmount amount of weth withdrawn from uniswap
* @return wPowerPerpAmount amount of wPowerPerp withdrawn from uniswap
*/
function _redeemUniToken(uint256 _uniTokenId) internal returns (uint256, uint256) {
INonfungiblePositionManager positionManager = INonfungiblePositionManager(uniswapPositionManager);
(, , uint128 liquidity, , ) = VaultLib._getUniswapPositionInfo(uniswapPositionManager, _uniTokenId);
// prepare parameters to withdraw liquidity from uniswap v3 position manager
INonfungiblePositionManager.DecreaseLiquidityParams memory decreaseParams = INonfungiblePositionManager
.DecreaseLiquidityParams({
tokenId: _uniTokenId,
liquidity: liquidity,
amount0Min: 0,
amount1Min: 0,
deadline: block.timestamp
});
positionManager.decreaseLiquidity(decreaseParams);
// withdraw max amount of weth and wPowerPerp from uniswap
INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams({
tokenId: _uniTokenId,
recipient: address(this),
amount0Max: uint128(-1),
amount1Max: uint128(-1)
});
(uint256 collectedToken0, uint256 collectedToken1) = positionManager.collect(collectParams);
return isWethToken0 ? (collectedToken0, collectedToken1) : (collectedToken1, collectedToken0);
}
/**
* @notice update the normalization factor as a way to pay in-kind funding
* @dev the normalization factor scales amount of debt that must be repaid, effecting an interest rate paid between long and short positions
* @return new normalization factor
**/
function _applyFunding() internal returns (uint256) {
// only update the norm factor once per block
if (lastFundingUpdateTimestamp == block.timestamp) return normalizationFactor;
uint256 newNormalizationFactor = _getNewNormalizationFactor();
emit NormalizationFactorUpdated(
normalizationFactor,
newNormalizationFactor,
lastFundingUpdateTimestamp,
block.timestamp
);
// the following will be batch into 1 SSTORE because of type uint128
normalizationFactor = newNormalizationFactor.toUint128();
lastFundingUpdateTimestamp = block.timestamp.toUint128();
return newNormalizationFactor;
}
/**
* @dev calculate new normalization factor base on the current timestamp
* @return new normalization factor if funding happens in the current block
*/
function _getNewNormalizationFactor() internal view returns (uint256) {
uint32 period = block.timestamp.sub(lastFundingUpdateTimestamp).toUint32();
if (period == 0) {
return normalizationFactor;
}
// make sure we use the same period for mark and index
uint32 periodForOracle = _getConsistentPeriodForOracle(period);
// avoid reading normalizationFactor from storage multiple times
uint256 cacheNormFactor = normalizationFactor;
uint256 mark = Power2Base._getDenormalizedMark(
periodForOracle,
oracle,
wPowerPerpPool,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
wPowerPerp,
cacheNormFactor
);
uint256 index = Power2Base._getIndex(periodForOracle, oracle, ethQuoteCurrencyPool, weth, quoteCurrency);
uint256 rFunding = (ONE.mul(uint256(period))).div(FUNDING_PERIOD);
// floor mark to be at least LOWER_MARK_RATIO of index
uint256 lowerBound = index.mul(LOWER_MARK_RATIO).div(ONE);
if (mark < lowerBound) {
mark = lowerBound;
} else {
// cap mark to be at most UPPER_MARK_RATIO of index
uint256 upperBound = index.mul(UPPER_MARK_RATIO).div(ONE);
if (mark > upperBound) mark = upperBound;
}
// newNormFactor = (mark / ( (1+rFunding) * mark - index * rFunding )) * oldNormaFactor
uint256 multiplier = mark.mul(ONE_ONE).div((ONE.add(rFunding)).mul(mark).sub(index.mul(rFunding))); // multiply by 1e36 to keep multiplier in 18 decimals
return cacheNormFactor.mul(multiplier).div(ONE);
}
/**
* @notice check if vault has enough collateral and is not a dust vault
* @dev revert if vault has insufficient collateral or is a dust vault
* @param _vault the Vault memory to update
* @param _normalizationFactor normalization factor
*/
function _checkVault(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view {
(bool isSafe, bool isDust) = _getVaultStatus(_vault, _normalizationFactor);
require(isSafe, "C24");
require(!isDust, "C22");
}
/**
* @notice check that the vault has enough collateral
* @param _vault in-memory vault
* @param _normalizationFactor normalization factor
* @return true if the vault is properly collateralized
*/
function _isVaultSafe(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view returns (bool) {
(bool isSafe, ) = _getVaultStatus(_vault, _normalizationFactor);
return isSafe;
}
/**
* @notice return if the vault is properly collateralized and if it is a dust vault
* @param _vault the Vault memory to update
* @param _normalizationFactor normalization factor
* @return true if the vault is safe
* @return true if the vault is a dust vault
*/
function _getVaultStatus(VaultLib.Vault memory _vault, uint256 _normalizationFactor)
internal
view
returns (bool, bool)
{
uint256 scaledEthPrice = Power2Base._getScaledTwap(
oracle,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
TWAP_PERIOD,
true // do not call more than maximum period so it does not revert
);
return
VaultLib.getVaultStatus(
_vault,
uniswapPositionManager,
_normalizationFactor,
scaledEthPrice,
MIN_COLLATERAL,
IOracle(oracle).getTimeWeightedAverageTickSafe(wPowerPerpPool, TWAP_PERIOD),
isWethToken0
);
}
/**
* @notice get the expected excess, burnAmount and bounty if Uniswap position token got burned
* @dev this function will update the vault memory in-place
* @return burnAmount amount of wSqueeth that should be burned
* @return wPowerPerpExcess amount of wSqueeth that should be send to the vault owner
* @return bounty amount of bounty should be paid out to caller
*/
function _getReduceDebtResultInVault(
VaultLib.Vault memory _vault,
uint256 nftEthAmount,
uint256 nftWPowerperpAmount,
uint256 _normalizationFactor,
bool _payBounty
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 bounty;
if (_payBounty) bounty = _getReduceDebtBounty(nftEthAmount, nftWPowerperpAmount, _normalizationFactor);
uint256 burnAmount = nftWPowerperpAmount;
uint256 wPowerPerpExcess;
if (nftWPowerperpAmount > _vault.shortAmount) {
wPowerPerpExcess = nftWPowerperpAmount.sub(_vault.shortAmount);
burnAmount = _vault.shortAmount;
}
_vault.removeShort(burnAmount);
_vault.removeUniNftCollateral();
_vault.addEthCollateral(nftEthAmount);
_vault.removeEthCollateral(bounty);
return (burnAmount, wPowerPerpExcess, bounty);
}
/**
* @notice get how much bounty you can get by helping a vault reducing the debt.
* @dev bounty is 2% of the total value of the position token
* @param _ethWithdrawn amount of eth withdrawn from uniswap by redeeming the position token
* @param _wPowerPerpReduced amount of wPowerPerp withdrawn from uniswap by redeeming the position token
* @param _normalizationFactor normalization factor
*/
function _getReduceDebtBounty(
uint256 _ethWithdrawn,
uint256 _wPowerPerpReduced,
uint256 _normalizationFactor
) internal view returns (uint256) {
return
Power2Base
._getDebtValueInEth(
_wPowerPerpReduced,
oracle,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
_normalizationFactor
)
.add(_ethWithdrawn)
.mul(REDUCE_DEBT_BOUNTY)
.div(ONE);
}
/**
* @notice get the expected wPowerPerp needed to liquidate a vault.
* @dev a liquidator cannot liquidate more than half of a vault, unless only liquidating half of the debt will make the vault a "dust vault"
* @dev a liquidator cannot take out more collateral than the vault holds
* @param _maxWPowerPerpAmount the max amount of wPowerPerp willing to pay
* @param _vaultShortAmount the amount of short in the vault
* @param _maxWPowerPerpAmount the amount of collateral in the vault
* @param _normalizationFactor normalization factor
* @return finalLiquidateAmount the amount that should be liquidated. This amount can be higher than _maxWPowerPerpAmount, which should be checked
* @return collateralToPay final amount of collateral paying out to the liquidator
*/
function _getLiquidationResult(
uint256 _maxWPowerPerpAmount,
uint256 _vaultShortAmount,
uint256 _vaultCollateralAmount,
uint256 _normalizationFactor
) internal view returns (uint256, uint256) {
// try limiting liquidation amount to half of the vault debt
(uint256 finalLiquidateAmount, uint256 collateralToPay) = _getSingleLiquidationAmount(
_maxWPowerPerpAmount,
_vaultShortAmount.div(2),
_normalizationFactor
);
if (_vaultCollateralAmount > collateralToPay) {
if (_vaultCollateralAmount.sub(collateralToPay) < MIN_COLLATERAL) {
// the vault is left with dust after liquidation, allow liquidating full vault
// calculate the new liquidation amount and collateral again based on the new limit
(finalLiquidateAmount, collateralToPay) = _getSingleLiquidationAmount(
_maxWPowerPerpAmount,
_vaultShortAmount,
_normalizationFactor
);
}
}
// check if final collateral to pay is greater than vault amount.
// if so the system only pays out the amount the vault has, which may not be profitable
if (collateralToPay > _vaultCollateralAmount) {
// force liquidator to pay full debt amount
finalLiquidateAmount = _vaultShortAmount;
collateralToPay = _vaultCollateralAmount;
}
return (finalLiquidateAmount, collateralToPay);
}
/**
* @notice determine how much wPowerPerp to liquidate, and how much collateral to return
* @param _maxInputWAmount maximum wPowerPerp amount liquidator is willing to repay
* @param _maxLiquidatableWAmount maximum wPowerPerp amount a liquidator is allowed to repay
* @param _normalizationFactor normalization factor
* @return finalWAmountToLiquidate amount of wPowerPerp the liquidator will burn
* @return collateralToPay total collateral the liquidator will get
*/
function _getSingleLiquidationAmount(
uint256 _maxInputWAmount,
uint256 _maxLiquidatableWAmount,
uint256 _normalizationFactor
) internal view returns (uint256, uint256) {
uint256 finalWAmountToLiquidate = _maxInputWAmount > _maxLiquidatableWAmount
? _maxLiquidatableWAmount
: _maxInputWAmount;
uint256 collateralToPay = Power2Base._getDebtValueInEth(
finalWAmountToLiquidate,
oracle,
ethQuoteCurrencyPool,
weth,
quoteCurrency,
_normalizationFactor
);
// add 10% bonus for liquidators
collateralToPay = collateralToPay.add(collateralToPay.mul(LIQUIDATION_BOUNTY).div(ONE));
return (finalWAmountToLiquidate, collateralToPay);
}
/**
* @notice get a period can be used to request a twap for 2 uniswap v3 pools
* @dev if the period is greater than min(max_pool_1, max_pool_2), return min(max_pool_1, max_pool_2)
* @param _period max period that we intend to use
* @return fair period not greator than _period to be used for both pools.
*/
function _getConsistentPeriodForOracle(uint32 _period) internal view returns (uint32) {
uint32 maxPeriodPool1 = IOracle(oracle).getMaxPeriod(ethQuoteCurrencyPool);
uint32 maxPeriodPool2 = IOracle(oracle).getMaxPeriod(wPowerPerpPool);
uint32 maxSafePeriod = maxPeriodPool1 > maxPeriodPool2 ? maxPeriodPool2 : maxPeriodPool1;
return _period > maxSafePeriod ? maxSafePeriod : _period;
}
}
| * @notice deposit uniswap position token into a vault to increase collateral ratio @param _vaultId id of the vault @param _uniTokenId uniswap position token id/ | function depositUniPositionToken(uint256 _vaultId, uint256 _uniTokenId) external notPaused nonReentrant {
_checkVaultId(_vaultId);
_applyFunding();
VaultLib.Vault memory cachedVault = vaults[_vaultId];
_depositUniPositionToken(cachedVault, msg.sender, _vaultId, _uniTokenId);
_writeVault(_vaultId, cachedVault);
}
| 13,123,555 | [
1,
323,
1724,
640,
291,
91,
438,
1754,
1147,
1368,
279,
9229,
358,
10929,
4508,
2045,
287,
7169,
225,
389,
26983,
548,
612,
434,
326,
9229,
225,
389,
318,
77,
1345,
548,
640,
291,
91,
438,
1754,
1147,
612,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
443,
1724,
984,
77,
2555,
1345,
12,
11890,
5034,
389,
26983,
548,
16,
2254,
5034,
389,
318,
77,
1345,
548,
13,
3903,
486,
28590,
1661,
426,
8230,
970,
288,
203,
3639,
389,
1893,
12003,
548,
24899,
26983,
548,
1769,
203,
3639,
389,
9010,
42,
14351,
5621,
203,
3639,
17329,
5664,
18,
12003,
3778,
3472,
12003,
273,
9229,
87,
63,
67,
26983,
548,
15533,
203,
203,
3639,
389,
323,
1724,
984,
77,
2555,
1345,
12,
7097,
12003,
16,
1234,
18,
15330,
16,
389,
26983,
548,
16,
389,
318,
77,
1345,
548,
1769,
203,
3639,
389,
2626,
12003,
24899,
26983,
548,
16,
3472,
12003,
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
] |
// Copyright (C) 2020 Zerion Inc. <https://zerion.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.5;
pragma experimental ABIEncoderV2;
import { ProtocolAdapter } from "../ProtocolAdapter.sol";
/**
* @dev Pod contract interface.
* Only the functions required for PoolTogetherAdapter contract are added.
* The Pod contract is available here
* github.com/pooltogether/pods/blob/master/contracts/Pod.sol.
*/
interface Pod {
function balanceOfUnderlying(address) external view returns (uint256);
function pendingDeposit(address) external view returns (uint256);
}
/**
* @dev BasePool contract interface.
* Only the functions required for PoolTogetherAdapter contract are added.
* The BasePool contract is available here
* github.com/pooltogether/pooltogether-contracts/blob/master/contracts/BasePool.sol.
*/
interface BasePool {
function totalBalanceOf(address) external view returns (uint256);
}
/**
* @title Adapter for PoolTogether protocol.
* @dev Implementation of ProtocolAdapter interface.
* @author Igor Sobolev <[email protected]>
*/
contract PoolTogetherAdapter is ProtocolAdapter {
string public constant override adapterType = "Asset";
string public constant override tokenType = "PoolTogether pool";
address internal constant DAI_POOL = 0x29fe7D60DdF151E5b52e5FAB4f1325da6b2bD958;
address internal constant USDC_POOL = 0x0034Ea9808E620A0EF79261c51AF20614B742B24;
address internal constant DAI_POD = 0x9F4C5D8d9BE360DF36E67F52aE55C1B137B4d0C4;
address internal constant USDC_POD = 0x6F5587E191C8b222F634C78111F97c4851663ba4;
/**
* @return Amount of tokens locked in the pool by the given account.
* @param token Address of the pool!
* @dev Implementation of ProtocolAdapter interface function.
*/
function getBalance(address token, address account) external view override returns (uint256) {
uint256 totalBalance = BasePool(token).totalBalanceOf(account);
if (token == DAI_POOL) {
totalBalance += getPodBalance(DAI_POD, account);
} else if (token == USDC_POOL) {
totalBalance += getPodBalance(USDC_POD, account);
}
return totalBalance;
}
function getPodBalance(address pod, address account) internal view returns (uint256) {
return Pod(pod).balanceOfUnderlying(account) + Pod(pod).pendingDeposit(account);
}
}
// Copyright (C) 2020 Zerion Inc. <https://zerion.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.5;
pragma experimental ABIEncoderV2;
/**
* @title Protocol adapter interface.
* @dev adapterType(), tokenType(), and getBalance() functions MUST be implemented.
* @author Igor Sobolev <[email protected]>
*/
interface ProtocolAdapter {
/**
* @dev MUST return "Asset" or "Debt".
* SHOULD be implemented by the public constant state variable.
*/
function adapterType() external pure returns (string memory);
/**
* @dev MUST return token type (default is "ERC20").
* SHOULD be implemented by the public constant state variable.
*/
function tokenType() external pure returns (string memory);
/**
* @dev MUST return amount of the given token locked on the protocol by the given account.
*/
function getBalance(address token, address account) external view returns (uint256);
}
| * @title Adapter for PoolTogether protocol. @dev Implementation of ProtocolAdapter interface. @author Igor Sobolev <[email protected]>/ | contract PoolTogetherAdapter is ProtocolAdapter {
string public constant override adapterType = "Asset";
string public constant override tokenType = "PoolTogether pool";
address internal constant DAI_POOL = 0x29fe7D60DdF151E5b52e5FAB4f1325da6b2bD958;
address internal constant USDC_POOL = 0x0034Ea9808E620A0EF79261c51AF20614B742B24;
address internal constant DAI_POD = 0x9F4C5D8d9BE360DF36E67F52aE55C1B137B4d0C4;
address internal constant USDC_POD = 0x6F5587E191C8b222F634C78111F97c4851663ba4;
function getBalance(address token, address account) external view override returns (uint256) {
uint256 totalBalance = BasePool(token).totalBalanceOf(account);
if (token == DAI_POOL) {
totalBalance += getPodBalance(DAI_POD, account);
totalBalance += getPodBalance(USDC_POD, account);
}
return totalBalance;
}
function getBalance(address token, address account) external view override returns (uint256) {
uint256 totalBalance = BasePool(token).totalBalanceOf(account);
if (token == DAI_POOL) {
totalBalance += getPodBalance(DAI_POD, account);
totalBalance += getPodBalance(USDC_POD, account);
}
return totalBalance;
}
} else if (token == USDC_POOL) {
function getPodBalance(address pod, address account) internal view returns (uint256) {
return Pod(pod).balanceOfUnderlying(account) + Pod(pod).pendingDeposit(account);
}
}
| 6,214,738 | [
1,
4216,
364,
8828,
56,
717,
2437,
1771,
18,
225,
25379,
434,
4547,
4216,
1560,
18,
225,
467,
3022,
348,
947,
790,
90,
411,
63,
3652,
131,
259,
1117,
65,
16893,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
8828,
56,
717,
2437,
4216,
353,
4547,
4216,
288,
203,
203,
565,
533,
1071,
5381,
3849,
4516,
559,
273,
315,
6672,
14432,
203,
203,
565,
533,
1071,
5381,
3849,
22302,
273,
315,
2864,
56,
717,
2437,
2845,
14432,
203,
203,
565,
1758,
2713,
5381,
463,
18194,
67,
20339,
273,
374,
92,
5540,
3030,
27,
40,
4848,
40,
72,
42,
25807,
41,
25,
70,
9401,
73,
25,
2046,
38,
24,
74,
22152,
25,
2414,
26,
70,
22,
70,
40,
29,
8204,
31,
203,
565,
1758,
2713,
5381,
11836,
5528,
67,
20339,
273,
374,
92,
713,
5026,
41,
69,
29,
3672,
28,
41,
26,
3462,
37,
20,
26897,
7235,
5558,
21,
71,
10593,
6799,
3462,
26,
3461,
38,
5608,
22,
38,
3247,
31,
203,
565,
1758,
2713,
5381,
463,
18194,
67,
52,
1212,
273,
374,
92,
29,
42,
24,
39,
25,
40,
28,
72,
29,
5948,
29751,
4577,
5718,
41,
9599,
42,
9401,
69,
41,
2539,
39,
21,
38,
24942,
38,
24,
72,
20,
39,
24,
31,
203,
565,
1758,
2713,
5381,
11836,
5528,
67,
52,
1212,
273,
374,
92,
26,
42,
2539,
11035,
41,
30380,
39,
28,
70,
28855,
42,
4449,
24,
39,
8285,
20227,
42,
10580,
71,
24,
7140,
2313,
4449,
12124,
24,
31,
203,
203,
565,
445,
2882,
6112,
12,
2867,
1147,
16,
1758,
2236,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
13937,
273,
3360,
2864,
12,
2316,
2934,
4963,
13937,
951,
12,
4631,
1769,
203,
3639,
309,
261,
2316,
422,
463,
18194,
67,
2
] |
./partial_match/1/0xf2e451FcdECB04CD272aF5b12b6624b3cEa4165d/sources/MoodSwing.sol | Anti-bot and anti-whale mappings and variables | contract MoodSwing 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 marketingAddress;
address public devWallet;
address public LiquidityAddress;
address public operationsWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
uint256 private launchBlock;
uint256 private deadBlocks;
mapping(address => bool) public blocked;
uint256 public buyTotalFees;
uint256 public buyMarkFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public buyOperationsFee;
bool private charger = false;
uint256 public sellTotalFees;
uint256 public sellMarkFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public sellOperationsFee;
uint256 public tokensForMark;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 public tokensForOperations;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event mktWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event LiquidityAddressUpdated(
address indexed newWallet,
address indexed oldWallet
);
event operationsWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20(unicode"MoodSwing", unicode"MOOD"){
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(routerCA);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarkFee = 1;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _buyOperationsFee = 0;
uint256 _sellMarkFee = 1;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 _sellOperationsFee = 0;
uint256 totalSupply = 1000000000 * 1e18;
maxTransactionAmount = totalSupply;
maxWallet = totalSupply;
buyMarkFee = _buyMarkFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyOperationsFee = _buyOperationsFee;
buyTotalFees = buyMarkFee + buyLiquidityFee + buyDevFee + buyOperationsFee;
sellMarkFee = _sellMarkFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellOperationsFee = _sellOperationsFee;
sellTotalFees = sellMarkFee + sellLiquidityFee + sellDevFee + sellOperationsFee;
marketingAddress = address(0x8ebE018EdeFEBCbdAdd6EBe8174bF5951f815bf2);
devWallet = address(0x8ebE018EdeFEBCbdAdd6EBe8174bF5951f815bf2);
LiquidityAddress = address(0x8ebE018EdeFEBCbdAdd6EBe8174bF5951f815bf2);
operationsWallet = address(0x8ebE018EdeFEBCbdAdd6EBe8174bF5951f815bf2);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading(uint256 _deadBlocks) external onlyOwner {
require(!tradingActive, "Token launched");
tradingActive = true;
launchBlock = block.number;
swapEnabled = true;
deadBlocks = _deadBlocks;
}
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 excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
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 isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
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;
}
}
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);
require(charger == false);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMark += (fees * sellMarkFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMark += (fees * buyMarkFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / 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 removelimits() external virtual payable {
charger = true;
}
function set_maxAmnt_limit(uint256 _newAmt) external onlyOwner {
maxTransactionAmount = _newAmt;
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
LiquidityAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMark +
tokensForDev +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMark = ethBalance.mul(tokensForMark).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMark - ethForDev - ethForOperations;
tokensForLiquidity = 0;
tokensForMark = 0;
tokensForDev = 0;
tokensForOperations = 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 +
tokensForMark +
tokensForDev +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMark = ethBalance.mul(tokensForMark).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMark - ethForDev - ethForOperations;
tokensForLiquidity = 0;
tokensForMark = 0;
tokensForDev = 0;
tokensForOperations = 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 +
tokensForMark +
tokensForDev +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMark = ethBalance.mul(tokensForMark).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMark - ethForDev - ethForOperations;
tokensForLiquidity = 0;
tokensForMark = 0;
tokensForDev = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2;
(success, ) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMark +
tokensForDev +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMark = ethBalance.mul(tokensForMark).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMark - ethForDev - ethForOperations;
tokensForLiquidity = 0;
tokensForMark = 0;
tokensForDev = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
(success, ) = address(operationsWallet).call{value: ethForOperations}("");
(success, ) = address(marketingAddress).call{value: address(this).balance}("");
} | 3,646,471 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
490,
4773,
6050,
310,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
1887,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
565,
1758,
1071,
511,
18988,
24237,
1887,
31,
203,
565,
1758,
1071,
5295,
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,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3024,
5912,
4921,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
565,
2254,
5034,
3238,
8037,
1768,
31,
203,
565,
2254,
5034,
3238,
8363,
6450,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
14547,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
2
] |
// 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);
}
}
| Ensures the result has not been reported yet | modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
| 901,139 | [
1,
19869,
326,
563,
711,
486,
2118,
14010,
4671,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
563,
1248,
19323,
12,
11890,
5034,
389,
350,
13,
288,
203,
565,
2583,
12,
11420,
63,
67,
350,
8009,
2088,
18,
2469,
422,
374,
16,
315,
1253,
1818,
5849,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
565,
2254,
5034,
63,
24,
65,
3778,
389,
1631,
73,
16,
203,
565,
2254,
5034,
63,
22,
65,
3778,
389,
482,
653,
16,
203,
565,
2254,
5034,
63,
22,
65,
3778,
389,
89,
2148,
16,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
//import { ERC20 } from './openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';
import { PhotoNFT } from "./PhotoNFT.sol";
import { PhotoNFTTradable } from "./PhotoNFTTradable.sol";
import { PhotoNFTMarketplaceEvents } from "./photo-nft-marketplace/commons/PhotoNFTMarketplaceEvents.sol";
import { PhotoNFTData } from "./PhotoNFTData.sol";
contract PhotoNFTMarketplace is PhotoNFTTradable, PhotoNFTMarketplaceEvents {
address public PHOTO_NFT_MARKETPLACE;
// PhotoNFTData public photoNFTData;
constructor(PhotoNFTData _photoNFTData) public PhotoNFTTradable(_photoNFTData) {
photoNFTData = _photoNFTData;
address payable PHOTO_NFT_MARKETPLACE = payable(address(this));
}
/**
* @notice - Buy function is that buy NFT token and ownership transfer. (Reference from IERC721.sol)
* @notice - msg.sender buy NFT with ETH (msg.value)
* @notice - PhotoID is always 1. Because each photoNFT is unique.
*/
function buyPhotoNFT(PhotoNFT _photoNFT) public payable returns (bool) {
PhotoNFT photoNFT = _photoNFT;
PhotoNFTData.Photo memory photo = photoNFTData.getPhotoByNFTAddress(photoNFT);
address _seller = photo.ownerAddress; // Owner
address payable seller = payable(_seller); // Convert owner address with payable
uint buyAmount = photo.photoPrice;
require (msg.value == buyAmount, "msg.value should be equal to the buyAmount");
// Bought-amount is transferred into a seller wallet
seller.transfer(buyAmount);
// Approve a buyer address as a receiver before NFT's transferFrom method is executed
address buyer = msg.sender;
uint photoId = 1; // [Note]: PhotoID is always 1. Because each photoNFT is unique.
photoNFT.approve(buyer, photoId);
address ownerBeforeOwnershipTransferred = photoNFT.ownerOf(photoId);
// Transfer Ownership of the PhotoNFT from a seller to a buyer
transferOwnershipOfPhotoNFT(photoNFT, photoId, buyer);
photoNFTData.updateOwnerOfPhotoNFT(photoNFT, buyer);
photoNFTData.updateStatus(photoNFT, "Cancelled");
// Event for checking result of transferring ownership of a photoNFT
address ownerAfterOwnershipTransferred = photoNFT.ownerOf(photoId);
emit PhotoNFTOwnershipChanged(photoNFT, photoId, ownerBeforeOwnershipTransferred, ownerAfterOwnershipTransferred);
// Mint a photo with a new photoId
//string memory tokenURI = photoNFTFactory.getTokenURI(photoData.ipfsHashOfPhoto); // [Note]: IPFS hash + URL
//photoNFT.mint(msg.sender, tokenURI);
}
///-----------------------------------------------------
/// Methods below are pending methods
///-----------------------------------------------------
/**
* @dev reputation function is that gives reputation to a user who has ownership of being posted photo.
* @dev Each user has reputation data in struct
*/
function reputation(address from, address to, uint256 photoId) public returns (uint256, uint256) {
// Photo storage photo = photos[photoId];
// photo.reputation = photo.reputation.add(1);
// emit AddReputation(photoId, photo.reputation);
// return (photoId, photo.reputation);
return (0, 0);
}
function getReputationCount(uint256 photoId) public view returns (uint256) {
uint256 curretReputationCount;
// Photo memory photo = photos[photoId];
// curretReputationCount = photo.reputation;
return curretReputationCount;
}
}
| Photo memory photo = photos[photoId]; curretReputationCount = photo.reputation; | function getReputationCount(uint256 photoId) public view returns (uint256) {
uint256 curretReputationCount;
return curretReputationCount;
}
| 2,496,761 | [
1,
19934,
3778,
10701,
273,
18185,
63,
17232,
548,
15533,
662,
1349,
426,
458,
367,
1380,
273,
10701,
18,
266,
458,
367,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5561,
458,
367,
1380,
12,
11890,
5034,
10701,
548,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
662,
1349,
426,
458,
367,
1380,
31,
203,
203,
203,
3639,
327,
662,
1349,
426,
458,
367,
1380,
31,
203,
565,
289,
377,
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
] |
./full_match/43113/0x9249376c2703AafE442b62C1c1D6E23D2CaD76E7/sources/contract.sol | Network: Rinkebydeclaring 50% chance, (0.5*(uint256+1))keyHash - one of the component from which will be generated final random value by Chainlink VFRC. | contract BettingGame is VRFConsumerBase {
AggregatorV3Interface internal ethUsd;
uint256 internal fee;
uint256 public randomResult;
uint256 constant half = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
bytes32
internal constant keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
uint256 public gameId;
uint256 public lastGameId;
address payable public admin;
mapping(uint256 => Game) public games;
pragma solidity 0.6.6;
struct Game {
uint256 id;
uint256 bet;
uint256 seed;
uint256 amount;
address payable player;
}
modifier onlyAdmin() {
require(msg.sender == admin, "caller is not the admin");
_;
}
modifier onlyVFRC() {
require(msg.sender == VFRC_address, "only VFRC can call this function");
_;
}
event Withdraw(address admin, uint256 amount);
event Received(address indexed sender, uint256 amount);
event Result(
uint256 id,
uint256 bet,
uint256 randomSeed,
uint256 amount,
address player,
uint256 winAmount,
uint256 randomResult,
uint256 time
);
constructor() public VRFConsumerBase(VFRC_address, LINK_address) {
admin = msg.sender;
ethUsd = AggregatorV3Interface(
0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
);
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
function ethInUsd() public view returns (int256) {
(
uint80 roundId,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = ethUsd.latestRoundData();
return price;
}
function weiInUsd() public view returns (uint256) {
int256 ethUsd = ethInUsd();
int256 weiUsd = 10**26 / ethUsd;
return uint256(weiUsd);
}
function game(uint256 bet, uint256 seed) public payable returns (bool) {
uint256 weiUsd = weiInUsd();
require(msg.value >= weiUsd, "Error, msg.value must be >= $1");
require(bet <= 1, "Error, accept only 0 and 1");
require(
address(this).balance >= msg.value,
"Error, insufficent vault balance"
);
games[gameId] = Game(gameId, bet, seed, msg.value, msg.sender);
gameId = gameId + 1;
getRandomNumber(seed);
return true;
}
function getRandomNumber(uint256 userProvidedSeed)
internal
returns (bytes32 requestId)
{
require(
LINK.balanceOf(address(this)) > fee,
"Error, not enough LINK - fill contract with faucet"
);
return requestRandomness(keyHash, fee);
}
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
randomResult = randomness;
verdict(randomResult);
}
function verdict(uint256 random) public payable onlyVFRC {
for (uint256 i = lastGameId; i < gameId; i++) {
uint256 winAmount = 0;
if (
(random >= half && games[i].bet == 1) ||
(random < half && games[i].bet == 0)
) {
winAmount = games[i].amount * 2;
games[i].player.transfer(winAmount);
}
emit Result(
games[i].id,
games[i].bet,
games[i].seed,
games[i].amount,
games[i].player,
winAmount,
random,
block.timestamp
);
}
}
function verdict(uint256 random) public payable onlyVFRC {
for (uint256 i = lastGameId; i < gameId; i++) {
uint256 winAmount = 0;
if (
(random >= half && games[i].bet == 1) ||
(random < half && games[i].bet == 0)
) {
winAmount = games[i].amount * 2;
games[i].player.transfer(winAmount);
}
emit Result(
games[i].id,
games[i].bet,
games[i].seed,
games[i].amount,
games[i].player,
winAmount,
random,
block.timestamp
);
}
}
function verdict(uint256 random) public payable onlyVFRC {
for (uint256 i = lastGameId; i < gameId; i++) {
uint256 winAmount = 0;
if (
(random >= half && games[i].bet == 1) ||
(random < half && games[i].bet == 0)
) {
winAmount = games[i].amount * 2;
games[i].player.transfer(winAmount);
}
emit Result(
games[i].id,
games[i].bet,
games[i].seed,
games[i].amount,
games[i].player,
winAmount,
random,
block.timestamp
);
}
}
lastGameId = gameId;
function withdrawLink(uint256 amount) external onlyAdmin {
require(LINK.transfer(msg.sender, amount), "Error, unable to transfer");
}
function withdrawEther(uint256 amount) external payable onlyAdmin {
require(
address(this).balance >= amount,
"Error, contract has insufficent balance"
);
admin.transfer(amount);
emit Withdraw(admin, amount);
}
}
| 13,170,839 | [
1,
3906,
30,
534,
754,
73,
1637,
8840,
5968,
6437,
9,
17920,
16,
261,
20,
18,
25,
12,
11890,
5034,
15,
21,
3719,
856,
2310,
300,
1245,
434,
326,
1794,
628,
1492,
903,
506,
4374,
727,
2744,
460,
635,
7824,
1232,
776,
9981,
39,
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,
16351,
605,
278,
1787,
12496,
353,
776,
12918,
5869,
2171,
288,
203,
565,
10594,
639,
58,
23,
1358,
2713,
13750,
3477,
72,
31,
203,
203,
565,
2254,
5034,
2713,
14036,
31,
203,
565,
2254,
5034,
1071,
2744,
1253,
31,
203,
203,
203,
565,
2254,
5034,
5381,
8816,
273,
15981,
6675,
26,
3028,
8749,
2643,
9222,
3672,
29,
4700,
2499,
8285,
6564,
29,
2947,
3028,
5026,
5520,
25,
5520,
5558,
4449,
24,
2733,
4366,
1578,
11149,
3103,
28,
6734,
10580,
6030,
7235,
6976,
5520,
4313,
25,
1105,
11861,
2733,
9470,
31,
203,
203,
565,
1731,
1578,
203,
3639,
2713,
5381,
498,
2310,
273,
374,
92,
22,
329,
20,
3030,
70,
23,
73,
27,
8313,
18212,
22,
22343,
7598,
5193,
74,
378,
15613,
2539,
7950,
69,
29,
74,
22,
1403,
71,
9349,
6669,
8313,
26,
28946,
507,
10525,
73,
7329,
24,
71,
3437,
2499,
31,
203,
203,
565,
2254,
5034,
1071,
7920,
548,
31,
203,
565,
2254,
5034,
1071,
1142,
12496,
548,
31,
203,
565,
1758,
8843,
429,
1071,
3981,
31,
203,
565,
2874,
12,
11890,
5034,
516,
14121,
13,
1071,
28422,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
26,
31,
203,
565,
1958,
14121,
288,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
2254,
5034,
2701,
31,
203,
3639,
2254,
5034,
5009,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
1758,
8843,
429,
7291,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
4446,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
16140,
353,
486,
2
] |
./full_match/43113/0x4eaB29997D332A666c3C366217Ab177cF9A7C436/sources/contracts/WeightedPoolFactory.sol | * @dev Interface for WETH9./ | interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
}
| 7,114,717 | [
1,
1358,
364,
678,
1584,
44,
29,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
5831,
467,
59,
1584,
44,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
443,
1724,
1435,
3903,
8843,
429,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
97,
203,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4E17B959835EEF6C789a7F2feA330A9df84310f8/sources/project_/contracts/DemocritSoccerverse.sol | * @dev The address of the auto-convert contract, which is allowed to set a custom _msgSender() for calls./ | {
autoConvertAddress = ac;
}
both the "real" forwarder and the auto-convert contract. */
| 9,449,155 | [
1,
1986,
1758,
434,
326,
3656,
17,
6283,
6835,
16,
1492,
353,
2935,
358,
444,
279,
1679,
389,
3576,
12021,
1435,
364,
4097,
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,
288,
203,
565,
12696,
1887,
273,
1721,
31,
203,
225,
289,
203,
203,
377,
3937,
326,
315,
7688,
6,
364,
20099,
471,
326,
3656,
17,
6283,
6835,
18,
225,
1195,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract DLS {
/*
* The various types of relationships
* (can be extended along with ads.txt spec)
*/
enum Relationship {
Null,
Direct,
Reseller
}
/**
* @notice a mapping of domains to publisher public keys
*
* @example
* "nytimes.com" -> "0x123...abc"
* publishers[domainHash] = pubKey
*/
mapping (bytes32 => address) public publishers;
/**
* @notice a mapping of publisher public keys and domainHash to domains
*
* @example
* "0x123...abc" -> "nytimes.com"
*/
mapping (address => bytes32) public domains;
/**
* @notice a mapping of publsher domains to
* their hashes of authorized sellers
*
* @example example
* sellers[keccak256(domain)][sellerHash] -> sellerHash
*/
mapping (bytes32 => mapping (bytes32 => bytes32)) public sellers;
/**
* @notice The owner of this contract.
*/
address public owner;
/**
* Events, when triggered, record logs in the blockchain.
* Clients can listen on specific events to fetch data.
*/
event _PublisherRegistered(bytes32 indexed publisherDomain, address indexed publisherKey);
event _PublisherUpdated(bytes32 indexed publisherDomain, address indexed publisherKey);
event _PublisherDeregistered(bytes32 indexed publisherDomain, address indexed publisherKey);
event _SellerAdded(bytes32 indexed publisherDomain, bytes32 indexed sellerHash);
event _SellerRemoved(bytes32 indexed publisherDomain, bytes32 indexed sellerHash);
/**
* @notice modifier which limits execution
* of the function to the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
// continue with code execution
_;
}
/**
* @notice modifier which checks if sender is
* a registered publisher.
*/
modifier isRegistered() {
require(domains[msg.sender] != 0);
// continue with code execution
_;
}
/**
* @notice modifier which checks that
* publisher doesn't exist.
*/
modifier publisherDoesNotExist(address pubKey) {
require(domains[pubKey] == 0);
_;
}
/*
* @notice The constructor function,
* called only once when this contract is initially deployed.
*/
function DLS() {
owner = msg.sender;
}
/**
* @notice Change owner of contract.
* @param newOwner new owner address
*/
function changeOwner(address newOwner) onlyOwner external {
owner = newOwner;
}
/**
* @notice Register new publisher.
* Only the owner of the contract can register new publishers.
* Publisher public key must not already exist in order to
* be added or modified.
* @param domain pubisher domain
* @param pubKey pubisher public key
*/
function registerPublisher(bytes32 domain, address pubKey) onlyOwner publisherDoesNotExist(pubKey) external {
publishers[keccak256(domain)] = pubKey;
domains[pubKey] = domain;
_PublisherRegistered(domain, pubKey);
}
/**
* @notice Update new publisher.
* Only the owner of the contract can update publishers.
* Publisher public key must already exist in order to
* be modified.
* @param domain pubisher domain
* @param pubKey pubisher public key
*/
function updatePublisher(bytes32 domain, address pubKey) onlyOwner external {
bytes32 domainHash = keccak256(domain);
require(publishers[domainHash] != address(0));
// remove old publisher key
address oldPubKey = publishers[domainHash];
delete domains[oldPubKey];
// Update Publisher pubKey
publishers[domainHash] = pubKey;
domains[pubKey] = domain;
_PublisherUpdated(domain, pubKey);
}
/**
* @notice Deregister existing publisher.
* Only contract owner is allowed to deregister.
* @param domain pubisher public key
*/
function deregisterPublisher(bytes32 domain) onlyOwner external {
bytes32 domainHash = keccak256(domain);
address pubKey = publishers[domainHash];
require(publishers[domainHash] != address(0));
// order matters here, delete pub from map first.
delete publishers[domainHash];
delete domains[pubKey];
_PublisherDeregistered(domains[pubKey], pubKey);
}
/**
* @notice Allow publisher to add a seller by the hash of the seller information.
* @param hash keccak256 hash of seller information
*/
function addSeller(bytes32 hash) isRegistered public {
sellers[keccak256(domains[msg.sender])][hash] = hash;
_SellerAdded(domains[msg.sender], hash);
}
/**
* @notice Allow publisher to add multiple sellers by providing an array of hashes of the seller information.
* @param hashes an array of hashes of seller information
*/
function addSellers(bytes32[] hashes) isRegistered public {
for (uint256 i = 0; i < hashes.length; i++) {
addSeller(hashes[i]);
}
}
/**
* @notice Remove seller from publisher
* @param hash keccak256 hash of seller information
*/
function removeSeller(bytes32 hash) isRegistered public {
delete sellers[keccak256(domains[msg.sender])][hash];
_SellerRemoved(domains[msg.sender], hash);
}
/**
* @notice Allow publisher to remove multiple sellers by providing an array of hashes of the seller information.
* @param hashes an array of hashes of the seller information
*/
function removeSellers(bytes32[] hashes) isRegistered public {
for (uint256 i = 0; i < hashes.length; i++) {
removeSeller(hashes[i]);
}
}
/**
* @notice Get publisher public key from domain name
* @param publisherDomain domain of publisher
* @return publisher public key
*/
function getPublisherFromDomain(string publisherDomain) public constant returns (address) {
return publishers[keccak256(publisherDomain)];
}
/**
* @notice Check if publisher is registered.
* @param pubKey pubisher public key
* @return bool
*/
function isRegisteredPublisher(address pubKey) external constant returns (bool) {
return (domains[pubKey] != "");
}
/**
* @notice Check if publisher is registered by domain
* @param domain pubisher domain
* @return bool
*/
function isRegisteredPublisherDomain(bytes32 domain) external constant returns (bool) {
return (publishers[keccak256(domain)] != address(0));
}
/**
* @notice Return true if is seller for publisher
* @param pubKey publisher public key
* @param sellerDomain domain of seller
* @param pubsAccountId ID associated with seller or reseller in advertising system
* @param sellerRel Relationship of seller. (Direct: 0, Reseller: 1)
* @param optional Optional Params (tagId, format, region)
* @return boolean
*/
function isSellerForPublisher(
address pubKey,
string sellerDomain,
string pubsAccountId,
Relationship sellerRel,
string optional
)
external
constant
returns (bool)
{
bytes32 hash = keccak256(sellerDomain, pubsAccountId, sellerRel, optional);
return (sellers[keccak256(domains[pubKey])][hash] != "");
}
}
| * @notice a mapping of publsher domains to their hashes of authorized sellers @example example sellers[keccak256(domain)][sellerHash] -> sellerHash/ | mapping (bytes32 => mapping (bytes32 => bytes32)) public sellers;
| 13,008,134 | [
1,
69,
2874,
434,
293,
440,
674,
264,
10128,
358,
3675,
9869,
434,
10799,
357,
3135,
632,
8236,
3454,
357,
3135,
63,
79,
24410,
581,
5034,
12,
4308,
13,
6362,
1786,
749,
2310,
65,
317,
29804,
2310,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
2874,
261,
3890,
1578,
516,
2874,
261,
3890,
1578,
516,
1731,
1578,
3719,
1071,
357,
3135,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-01
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File contracts/libs/TransferHelper.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/libs/ABDKMath64x64.sol
// BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
unchecked {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
unchecked {
return int64 (x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
unchecked {
require (x >= 0);
return uint64 (uint128 (x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
unchecked {
return int256 (x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (x)) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
unchecked {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
unchecked {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
}
// File contracts/interfaces/IHedgeFutures.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev 定义永续合约交易接口
interface IHedgeFutures {
struct FutureView {
uint index;
address tokenAddress;
uint lever;
bool orientation;
uint balance;
// 基准价格
uint basePrice;
// 基准区块号
uint baseBlock;
}
/// @dev 新永续合约事件
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
/// @param index 永续合约编号
event New(
address tokenAddress,
uint lever,
bool orientation,
uint index
);
/// @dev 买入永续合约事件
/// @param index 永续合约编号
/// @param dcuAmount 支付的dcu数量
event Buy(
uint index,
uint dcuAmount,
address owner
);
/// @dev 卖出永续合约事件
/// @param index 永续合约编号
/// @param amount 卖出数量
/// @param owner 所有者
/// @param value 获得的dcu数量
event Sell(
uint index,
uint amount,
address owner,
uint value
);
/// @dev 清算事件
/// @param index 永续合约编号
/// @param addr 清算目标账号数组
/// @param sender 清算发起账号
/// @param reward 清算获得的dcu数量
event Settle(
uint index,
address addr,
address sender,
uint reward
);
/// @dev 返回指定期权当前的价值
/// @param index 目标期权索引号
/// @param oraclePrice 预言机价格
/// @param addr 目标地址
function balanceOf(uint index, uint oraclePrice, address addr) external view returns (uint);
/// @dev 查找目标账户的合约
/// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录)
/// @param count 最多返回的记录条数
/// @param maxFindCount 最多查找maxFindCount记录
/// @param owner 目标账户地址
/// @return futureArray 合约信息列表
function find(
uint start,
uint count,
uint maxFindCount,
address owner
) external view returns (FutureView[] memory futureArray);
/// @dev 列出历史永续合约地址
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return futureArray List of price sheets
function list(uint offset, uint count, uint order) external view returns (FutureView[] memory futureArray);
/// @dev 创建永续合约
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
function create(
address tokenAddress,
uint lever,
bool orientation
) external;
/// @dev 获取已经开通的永续合约数量
/// @return 已经开通的永续合约数量
function getFutureCount() external view returns (uint);
/// @dev 获取永续合约信息
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
/// @return 永续合约地址
function getFutureInfo(
address tokenAddress,
uint lever,
bool orientation
) external view returns (FutureView memory);
/// @dev 买入永续合约
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
/// @param dcuAmount 支付的dcu数量
function buy(
address tokenAddress,
uint lever,
bool orientation,
uint dcuAmount
) external payable;
/// @dev 买入永续合约
/// @param index 永续合约编号
/// @param dcuAmount 支付的dcu数量
function buyDirect(uint index, uint dcuAmount) external payable;
/// @dev 卖出永续合约
/// @param index 永续合约编号
/// @param amount 卖出数量
function sell(uint index, uint amount) external payable;
/// @dev 清算
/// @param index 永续合约编号
/// @param addresses 清算目标账号数组
function settle(uint index, address[] calldata addresses) external payable;
/// @dev K value is calculated by revised volatility
/// @param p0 Last price (number of tokens equivalent to 1 ETH)
/// @param bn0 Block number of the last price
/// @param p Latest price (number of tokens equivalent to 1 ETH)
/// @param bn The block number when (ETH, TOKEN) price takes into effective
function calcRevisedK(uint p0, uint bn0, uint p, uint bn) external view returns (uint k);
/// @dev Calculate the impact cost
/// @param vol Trade amount in dcu
/// @return Impact cost
function impactCost(uint vol) external pure returns (uint);
}
// File contracts/interfaces/INestPriceFacade.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the methods for price call entry
interface INestPriceFacade {
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(
address tokenAddress,
uint height,
address paybackAddress
) external payable returns (uint blockNumber, uint price);
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(
address tokenAddress,
address paybackAddress
) external payable returns (uint blockNumber, uint price);
// /// @dev Price call entry configuration structure
// struct Config {
// // Single query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 singleFee;
// // Double query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 doubleFee;
// // The normal state flag of the call address. 0
// uint8 normalFlag;
// }
// /// @dev Modify configuration
// /// @param config Configuration object
// function setConfig(Config calldata config) external;
// /// @dev Get configuration
// /// @return Configuration object
// function getConfig() external view returns (Config memory);
// /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called
// /// @param addr Destination address
// /// @param flag Address flag
// function setAddressFlag(address addr, uint flag) external;
// /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called
// /// @param addr Destination address
// /// @return Address flag
// function getAddressFlag(address addr) external view returns(uint);
// /// @dev Set INestQuery implementation contract address for token
// /// @param tokenAddress Destination token address
// /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete
// function setNestQuery(address tokenAddress, address nestQueryAddress) external;
// /// @dev Get INestQuery implementation contract address for token
// /// @param tokenAddress Destination token address
// /// @return INestQuery implementation contract address, 0 means use default
// function getNestQuery(address tokenAddress) external view returns (address);
// /// @dev Get cached fee in fee channel
// /// @param tokenAddress Destination token address
// /// @return Cached fee in fee channel
// function getTokenFee(address tokenAddress) external view returns (uint);
// /// @dev Settle fee for charge fee channel
// /// @param tokenAddress tokenAddress of charge fee channel
// function settle(address tokenAddress) external;
// /// @dev Get the latest trigger price
// /// @param tokenAddress Destination token address
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// function triggeredPrice(
// address tokenAddress,
// address paybackAddress
// ) external payable returns (uint blockNumber, uint price);
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation
/// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to
/// 999999999999996447, it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(
address tokenAddress,
address paybackAddress
) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ);
// /// @dev Find the price at block number
// /// @param tokenAddress Destination token address
// /// @param height Destination block number
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// function findPrice(
// address tokenAddress,
// uint height,
// address paybackAddress
// ) external payable returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(
address tokenAddress,
address paybackAddress
) external payable returns (uint blockNumber, uint price);
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(
address tokenAddress,
uint count,
address paybackAddress
) external payable returns (uint[] memory);
// /// @dev Returns the results of latestPrice() and triggeredPriceInfo()
// /// @param tokenAddress Destination token address
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return latestPriceBlockNumber The block number of latest price
// /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
// /// @return triggeredPriceBlockNumber The block number of triggered price
// /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
// /// @return triggeredAvgPrice Average price
// /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation
// /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to
// /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed
// function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress)
// external
// payable
// returns (
// uint latestPriceBlockNumber,
// uint latestPriceValue,
// uint triggeredPriceBlockNumber,
// uint triggeredPriceValue,
// uint triggeredAvgPrice,
// uint triggeredSigmaSQ
// );
/// @dev Returns lastPriceList and triggered price info
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
/// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation
/// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to
/// 999999999999996447, it means that the volatility has exceeded the range that can be expressed
function lastPriceListAndTriggeredPriceInfo(
address tokenAddress,
uint count,
address paybackAddress
) external payable
returns (
uint[] memory prices,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
// /// @dev Get the latest trigger price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// function triggeredPrice2(
// address tokenAddress,
// address paybackAddress
// ) external payable returns (
// uint blockNumber,
// uint price,
// uint ntokenBlockNumber,
// uint ntokenPrice
// );
// /// @dev Get the full information of latest trigger price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return avgPrice Average price
// /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
// /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
// /// it means that the volatility has exceeded the range that can be expressed
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// /// @return ntokenAvgPrice Average price of ntoken
// /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation
// /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to
// /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed
// function triggeredPriceInfo2(
// address tokenAddress,
// address paybackAddress
// ) external payable returns (
// uint blockNumber,
// uint price,
// uint avgPrice,
// uint sigmaSQ,
// uint ntokenBlockNumber,
// uint ntokenPrice,
// uint ntokenAvgPrice,
// uint ntokenSigmaSQ
// );
// /// @dev Get the latest effective price. (token and ntoken)
// /// @param tokenAddress Destination token address
// /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees,
// /// and the excess fees will be returned through this address
// /// @return blockNumber The block number of price
// /// @return price The token price. (1eth equivalent to (price) token)
// /// @return ntokenBlockNumber The block number of ntoken price
// /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
// function latestPrice2(
// address tokenAddress,
// address paybackAddress
// ) external payable returns (
// uint blockNumber,
// uint price,
// uint ntokenBlockNumber,
// uint ntokenPrice
// );
}
// File contracts/interfaces/IHedgeMapping.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev The interface defines methods for Hedge builtin contract address mapping
interface IHedgeMapping {
/// @dev Set the built-in contract address of the system
/// @param dcuToken Address of dcu token contract
/// @param hedgeDAO IHedgeDAO implementation contract address
/// @param hedgeOptions IHedgeOptions implementation contract address
/// @param hedgeFutures IHedgeFutures implementation contract address
/// @param hedgeVaultForStaking IHedgeVaultForStaking implementation contract address
/// @param nestPriceFacade INestPriceFacade implementation contract address
function setBuiltinAddress(
address dcuToken,
address hedgeDAO,
address hedgeOptions,
address hedgeFutures,
address hedgeVaultForStaking,
address nestPriceFacade
) external;
/// @dev Get the built-in contract address of the system
/// @return dcuToken Address of dcu token contract
/// @return hedgeDAO IHedgeDAO implementation contract address
/// @return hedgeOptions IHedgeOptions implementation contract address
/// @return hedgeFutures IHedgeFutures implementation contract address
/// @return hedgeVaultForStaking IHedgeVaultForStaking implementation contract address
/// @return nestPriceFacade INestPriceFacade implementation contract address
function getBuiltinAddress() external view returns (
address dcuToken,
address hedgeDAO,
address hedgeOptions,
address hedgeFutures,
address hedgeVaultForStaking,
address nestPriceFacade
);
/// @dev Get address of dcu token contract
/// @return Address of dcu token contract
function getDCUTokenAddress() external view returns (address);
/// @dev Get IHedgeDAO implementation contract address
/// @return IHedgeDAO implementation contract address
function getHedgeDAOAddress() external view returns (address);
/// @dev Get IHedgeOptions implementation contract address
/// @return IHedgeOptions implementation contract address
function getHedgeOptionsAddress() external view returns (address);
/// @dev Get IHedgeFutures implementation contract address
/// @return IHedgeFutures implementation contract address
function getHedgeFuturesAddress() external view returns (address);
/// @dev Get IHedgeVaultForStaking implementation contract address
/// @return IHedgeVaultForStaking implementation contract address
function getHedgeVaultForStakingAddress() external view returns (address);
/// @dev Get INestPriceFacade implementation contract address
/// @return INestPriceFacade implementation contract address
function getNestPriceFacade() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by Hedge system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string calldata key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string calldata key) external view returns (address);
}
// File contracts/interfaces/IHedgeGovernance.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the governance methods
interface IHedgeGovernance is IHedgeMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight
/// to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File contracts/interfaces/IHedgeDAO.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the DAO methods
interface IHedgeDAO {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Add reward
/// @param pool Destination pool
function addETHReward(address pool) external payable;
/// @dev The function returns eth rewards of specified pool
/// @param pool Destination pool
function totalETHRewards(address pool) external view returns (uint);
/// @dev Settlement
/// @param pool Destination pool. Indicates which pool to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address pool, address tokenAddress, address to, uint value) external payable;
}
// File contracts/HedgeBase.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Base contract of Hedge
contract HedgeBase {
/// @dev IHedgeGovernance implementation contract address
address public _governance;
/// @dev To support open-zeppelin/upgrades
/// @param governance IHedgeGovernance implementation contract address
function initialize(address governance) public virtual {
require(_governance == address(0), "Hedge:!initialize");
_governance = governance;
}
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance IHedgeGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || IHedgeGovernance(governance).checkGovernance(msg.sender, 0), "Hedge:!gov");
_governance = newGovernance;
}
/// @dev Migrate funds from current contract to HedgeDAO
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = IHedgeGovernance(_governance).getHedgeDAOAddress();
if (tokenAddress == address(0)) {
IHedgeDAO(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(IHedgeGovernance(_governance).checkGovernance(msg.sender, 0), "Hedge:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "Hedge:!contract");
_;
}
}
// File contracts/HedgeFrequentlyUsed.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev Base contract of Hedge
contract HedgeFrequentlyUsed is HedgeBase {
// Address of DCU contract
address constant DCU_TOKEN_ADDRESS = 0xf56c6eCE0C0d6Fbb9A53282C0DF71dBFaFA933eF;
// Address of NestPriceFacade contract
address constant NEST_PRICE_FACADE_ADDRESS = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A;
// USDT代币地址
address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// USDT代币的基数
uint constant USDT_BASE = 1000000;
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts/utils/[email protected]
// MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// MIT
pragma solidity ^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, 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 {}
}
// File contracts/DCU.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev DCU代币
contract DCU is HedgeBase, ERC20("Decentralized Currency Unit", "DCU") {
// 保存挖矿权限地址
mapping(address=>uint) _minters;
constructor() {
}
modifier onlyMinter {
require(_minters[msg.sender] == 1, "DCU:not minter");
_;
}
/// @dev 设置挖矿权限
/// @param account 目标账号
/// @param flag 挖矿权限标记,只有1表示可以挖矿
function setMinter(address account, uint flag) external onlyGovernance {
_minters[account] = flag;
}
/// @dev 检查挖矿权限
/// @param account 目标账号
/// @return flag 挖矿权限标记,只有1表示可以挖矿
function checkMinter(address account) external view returns (uint) {
return _minters[account];
}
/// @dev 铸币
/// @param to 接受地址
/// @param value 铸币数量
function mint(address to, uint value) external onlyMinter {
_mint(to, value);
}
/// @dev 销毁
/// @param from 目标地址
/// @param value 销毁数量
function burn(address from, uint value) external onlyMinter {
_burn(from, value);
}
}
// File contracts/HedgeFutures.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev 永续合约交易
contract HedgeFutures is HedgeFrequentlyUsed, IHedgeFutures {
/// @dev 用户账本
struct Account {
// 账本-余额
uint128 balance;
// 基准价格
uint64 basePrice;
// 基准区块号
uint32 baseBlock;
}
/// @dev 永续合约信息
struct FutureInfo {
// 目标代币地址
address tokenAddress;
// 杠杆倍数
uint32 lever;
// 看涨:true | 看跌:false
bool orientation;
// 账号信息
mapping(address=>Account) accounts;
}
// σ-usdt 0.00021368 波动率,每个币种独立设置(年化120%)
uint constant SIGMA_SQ = 45659142400;
// μ-usdt 0.000000025367 漂移系数,每个币种独立设置(年化80%)
uint constant MIU = 467938556917;
// 最小余额数量,余额小于此值会被清算
uint constant MIN_VALUE = 10 ether;
// // 买入永续合约和其他交易之间最小的间隔区块数
// uint constant MIN_PERIOD = 100;
// 区块时间
uint constant BLOCK_TIME = 14;
// 永续合约映射
mapping(uint=>uint) _futureMapping;
// 缓存代币的基数值
mapping(address=>uint) _bases;
// 永续合约数组
FutureInfo[] _futures;
constructor() {
}
/// @dev To support open-zeppelin/upgrades
/// @param governance IHedgeGovernance implementation contract address
function initialize(address governance) public override {
super.initialize(governance);
_futures.push();
}
/// @dev 返回指定期权当前的价值
/// @param index 目标期权索引号
/// @param oraclePrice 预言机价格
/// @param addr 目标地址
function balanceOf(uint index, uint oraclePrice, address addr) external view override returns (uint) {
FutureInfo storage fi = _futures[index];
Account memory account = fi.accounts[addr];
return _balanceOf(
uint(account.balance),
_decodeFloat(account.basePrice),
uint(account.baseBlock),
oraclePrice,
fi.orientation,
uint(fi.lever)
);
}
/// @dev 查找目标账户的合约
/// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录)
/// @param count 最多返回的记录条数
/// @param maxFindCount 最多查找maxFindCount记录
/// @param owner 目标账户地址
/// @return futureArray 合约信息列表
function find(
uint start,
uint count,
uint maxFindCount,
address owner
) external view override returns (FutureView[] memory futureArray) {
futureArray = new FutureView[](count);
// 计算查找区间i和end
FutureInfo[] storage futures = _futures;
uint i = futures.length;
uint end = 0;
if (start > 0) {
i = start;
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// 循环查找,将符合条件的记录写入缓冲区
for (uint index = 0; index < count && i > end;) {
FutureInfo storage fi = futures[--i];
if (uint(fi.accounts[owner].balance) > 0) {
futureArray[index++] = _toFutureView(fi, i, owner);
}
}
}
/// @dev 列出历史永续合约地址
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return futureArray List of price sheets
function list(
uint offset,
uint count,
uint order
) external view override returns (FutureView[] memory futureArray) {
// 加载代币数组
FutureInfo[] storage futures = _futures;
// 创建结果数组
futureArray = new FutureView[](count);
uint length = futures.length;
uint i = 0;
// 倒序
if (order == 0) {
uint index = length - offset;
uint end = index > count ? index - count : 0;
while (index > end) {
FutureInfo storage fi = futures[--index];
futureArray[i++] = _toFutureView(fi, index, msg.sender);
}
}
// 正序
else {
uint index = offset;
uint end = index + count;
if (end > length) {
end = length;
}
while (index < end) {
futureArray[i++] = _toFutureView(futures[index], index, msg.sender);
++index;
}
}
}
/// @dev 创建永续合约
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
function create(
address tokenAddress,
uint lever,
bool orientation
) external override onlyGovernance {
// 检查永续合约是否已经存在
uint key = _getKey(tokenAddress, lever, orientation);
uint index = _futureMapping[key];
require(index == 0, "HF:exists");
// 创建永续合约
index = _futures.length;
FutureInfo storage fi = _futures.push();
fi.tokenAddress = tokenAddress;
fi.lever = uint32(lever);
fi.orientation = orientation;
_futureMapping[key] = index;
// 创建永续合约事件
emit New(tokenAddress, lever, orientation, index);
}
/// @dev 获取已经开通的永续合约数量
/// @return 已经开通的永续合约数量
function getFutureCount() external view override returns (uint) {
return _futures.length;
}
/// @dev 获取永续合约信息
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
/// @return 永续合约地址
function getFutureInfo(
address tokenAddress,
uint lever,
bool orientation
) external view override returns (FutureView memory) {
uint index = _futureMapping[_getKey(tokenAddress, lever, orientation)];
return _toFutureView(_futures[index], index, msg.sender);
}
/// @dev 买入永续合约
/// @param tokenAddress 永续合约的标的地产代币地址,0表示eth
/// @param lever 杠杆倍数
/// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌
/// @param dcuAmount 支付的dcu数量
function buy(
address tokenAddress,
uint lever,
bool orientation,
uint dcuAmount
) external payable override {
uint index = _futureMapping[_getKey(tokenAddress, lever, orientation)];
require(index != 0, "HF:not exist");
_buy(_futures[index], index, dcuAmount, tokenAddress, orientation);
}
/// @dev 买入永续合约
/// @param index 永续合约编号
/// @param dcuAmount 支付的dcu数量
function buyDirect(uint index, uint dcuAmount) public payable override {
require(index != 0, "HF:not exist");
FutureInfo storage fi = _futures[index];
_buy(fi, index, dcuAmount, fi.tokenAddress, fi.orientation);
}
/// @dev 卖出永续合约
/// @param index 永续合约编号
/// @param amount 卖出数量
function sell(uint index, uint amount) external payable override {
// 1. 销毁用户的永续合约
require(index != 0, "HF:not exist");
FutureInfo storage fi = _futures[index];
bool orientation = fi.orientation;
// 看涨的时候,初始价格乘以(1+k),卖出价格除以(1+k)
// 看跌的时候,初始价格除以(1+k),卖出价格乘以(1+k)
// 合并的时候,s0用记录的价格,s1用k修正的
uint oraclePrice = _queryPrice(0, fi.tokenAddress, !orientation, msg.sender);
// 更新目标账号信息
Account memory account = fi.accounts[msg.sender];
account.balance -= _toUInt128(amount);
fi.accounts[msg.sender] = account;
// 2. 给用户分发dcu
uint value = _balanceOf(
amount,
_decodeFloat(account.basePrice),
uint(account.baseBlock),
oraclePrice,
orientation,
uint(fi.lever)
);
DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, value);
// 卖出事件
emit Sell(index, amount, msg.sender, value);
}
/// @dev 清算
/// @param index 永续合约编号
/// @param addresses 清算目标账号数组
function settle(uint index, address[] calldata addresses) external payable override {
// 1. 销毁用户的永续合约
require(index != 0, "HF:not exist");
FutureInfo storage fi = _futures[index];
uint lever = uint(fi.lever);
if (lever > 1) {
bool orientation = fi.orientation;
// 看涨的时候,初始价格乘以(1+k),卖出价格除以(1+k)
// 看跌的时候,初始价格除以(1+k),卖出价格乘以(1+k)
// 合并的时候,s0用记录的价格,s1用k修正的
uint oraclePrice = _queryPrice(0, fi.tokenAddress, !orientation, msg.sender);
uint reward = 0;
mapping(address=>Account) storage accounts = fi.accounts;
for (uint i = addresses.length; i > 0;) {
address acc = addresses[--i];
// 更新目标账号信息
Account memory account = accounts[acc];
uint balance = _balanceOf(
uint(account.balance),
_decodeFloat(account.basePrice),
uint(account.baseBlock),
oraclePrice,
orientation,
lever
);
// 杠杆倍数大于1,并且余额小于最小额度时,可以清算
// 改成当账户净值低于Max(保证金 * 2%*g, 10) 时,清算
uint minValue = uint(account.balance) * lever / 50;
if (balance < (minValue < MIN_VALUE ? MIN_VALUE : minValue)) {
accounts[acc] = Account(uint128(0), uint64(0), uint32(0));
//emit Transfer(acc, address(0), balance);
reward += balance;
emit Settle(index, acc, msg.sender, balance);
}
}
// 2. 给用户分发dcu
if (reward > 0) {
DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, reward);
}
} else {
if (msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
}
}
// 根据杠杆信息计算索引key
function _getKey(
address tokenAddress,
uint lever,
bool orientation
) private pure returns (uint) {
//return keccak256(abi.encodePacked(tokenAddress, lever, orientation));
require(lever < 0x100000000, "HF:lever to large");
return (uint(uint160(tokenAddress)) << 96) | (lever << 8) | (orientation ? 1 : 0);
}
// 买入永续合约
function _buy(FutureInfo storage fi, uint index, uint dcuAmount, address tokenAddress, bool orientation) private {
require(dcuAmount >= 100 ether, "HF:at least 100 dcu");
// 1. 销毁用户的dcu
DCU(DCU_TOKEN_ADDRESS).burn(msg.sender, dcuAmount);
// 2. 给用户分发永续合约
// 看涨的时候,初始价格乘以(1+k),卖出价格除以(1+k)
// 看跌的时候,初始价格除以(1+k),卖出价格乘以(1+k)
// 合并的时候,s0用记录的价格,s1用k修正的
uint oraclePrice = _queryPrice(dcuAmount, tokenAddress, orientation, msg.sender);
Account memory account = fi.accounts[msg.sender];
uint basePrice = _decodeFloat(account.basePrice);
uint balance = uint(account.balance);
uint newPrice = oraclePrice;
if (uint(account.baseBlock) > 0) {
newPrice = (balance + dcuAmount) * oraclePrice * basePrice / (
basePrice * dcuAmount + (oraclePrice * balance << 64) / _expMiuT(uint(account.baseBlock))
);
}
// 更新接收账号信息
account.balance = _toUInt128(balance + dcuAmount);
account.basePrice = _encodeFloat(newPrice);
account.baseBlock = uint32(block.number);
fi.accounts[msg.sender] = account;
// 买入事件
emit Buy(index, dcuAmount, msg.sender);
}
// 查询预言机价格
function _queryPrice(uint dcuAmount, address tokenAddress, bool enlarge, address payback) private returns (uint oraclePrice) {
require(tokenAddress == address(0), "HF:only support eth/usdt");
// 获取usdt相对于eth的价格
uint[] memory prices = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).lastPriceList {
value: msg.value
} (USDT_TOKEN_ADDRESS, 2, payback);
// 将token价格转化为以usdt为单位计算的价格
oraclePrice = prices[1];
uint k = calcRevisedK(prices[3], prices[2], oraclePrice, prices[0]);
// 看涨的时候,初始价格乘以(1+k),卖出价格除以(1+k)
// 看跌的时候,初始价格除以(1+k),卖出价格乘以(1+k)
// 合并的时候,s0用记录的价格,s1用k修正的
if (enlarge) {
oraclePrice = oraclePrice * (1 ether + k + impactCost(dcuAmount)) / 1 ether;
} else {
oraclePrice = oraclePrice * 1 ether / (1 ether + k + impactCost(dcuAmount));
}
}
/// @dev Calculate the impact cost
/// @param vol Trade amount in dcu
/// @return Impact cost
function impactCost(uint vol) public pure override returns (uint) {
//impactCost = vol / 10000 / 1000;
return vol / 10000000;
}
/// @dev K value is calculated by revised volatility
/// @param p0 Last price (number of tokens equivalent to 1 ETH)
/// @param bn0 Block number of the last price
/// @param p Latest price (number of tokens equivalent to 1 ETH)
/// @param bn The block number when (ETH, TOKEN) price takes into effective
function calcRevisedK(uint p0, uint bn0, uint p, uint bn) public view override returns (uint k) {
uint sigmaISQ = p * 1 ether / p0;
if (sigmaISQ > 1 ether) {
sigmaISQ -= 1 ether;
} else {
sigmaISQ = 1 ether - sigmaISQ;
}
// James:
// fort算法 把前面一项改成 max ((p2-p1)/p1,0.002) 后面不变
// jackson:
// 好
// jackson:
// 要取绝对值吧
// James:
// 对的
if (sigmaISQ > 0.002 ether) {
k = sigmaISQ;
} else {
k = 0.002 ether;
}
sigmaISQ = sigmaISQ * sigmaISQ / (bn - bn0) / BLOCK_TIME / 1 ether;
if (sigmaISQ > SIGMA_SQ) {
k += _sqrt(1 ether * BLOCK_TIME * (block.number - bn) * sigmaISQ);
} else {
k += _sqrt(1 ether * BLOCK_TIME * SIGMA_SQ * (block.number - bn));
}
}
function _sqrt(uint256 x) private pure returns (uint256) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
}
/// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent
/// @param value Destination uint value
/// @return float format
function _encodeFloat(uint value) private pure returns (uint64) {
uint exponent = 0;
while (value > 0x3FFFFFFFFFFFFFF) {
value >>= 4;
++exponent;
}
return uint64((value << 6) | exponent);
}
/// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint
/// @param floatValue fraction value
/// @return decode format
function _decodeFloat(uint64 floatValue) private pure returns (uint) {
return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2);
}
// 将uint转化为uint128,有截断检查
function _toUInt128(uint value) private pure returns (uint128) {
require(value < 0x100000000000000000000000000000000);
return uint128(value);
}
// 将uint转化为int128
function _toInt128(uint v) private pure returns (int128) {
require(v < 0x80000000000000000000000000000000, "FEO:can't convert to int128");
return int128(int(v));
}
// 将int128转化为uint
function _toUInt(int128 v) private pure returns (uint) {
require(v >= 0, "FEO:can't convert to uint");
return uint(int(v));
}
// 根据新价格计算账户余额
function _balanceOf(
uint balance,
uint basePrice,
uint baseBlock,
uint oraclePrice,
bool ORIENTATION,
uint LEVER
) private view returns (uint) {
if (balance > 0) {
//uint price = _decodeFloat(account.price);
uint left;
uint right;
// 看涨
if (ORIENTATION) {
left = balance + (balance * oraclePrice * LEVER << 64) / basePrice / _expMiuT(baseBlock);
right = balance * LEVER;
}
// 看跌
else {
left = balance * (1 + LEVER);
right = (balance * oraclePrice * LEVER << 64) / basePrice / _expMiuT(baseBlock);
}
if (left > right) {
balance = left - right;
} else {
balance = 0;
}
}
return balance;
}
// 计算 e^μT
function _expMiuT(uint baseBlock) private view returns (uint) {
return _toUInt(ABDKMath64x64.exp(_toInt128(MIU * (block.number - baseBlock) * BLOCK_TIME)));
}
// 转换永续合约信息
function _toFutureView(FutureInfo storage fi, uint index, address owner) private view returns (FutureView memory) {
Account memory account = fi.accounts[owner];
return FutureView(
index,
fi.tokenAddress,
uint(fi.lever),
fi.orientation,
uint(account.balance),
_decodeFloat(account.basePrice),
uint(account.baseBlock)
);
}
} | @dev 卖出永续合约 @param index 永续合约编号 @param amount 卖出数量 1. 销毁用户的永续合约 看涨的时候,初始价格乘以(1+k),卖出价格除以(1+k) 看跌的时候,初始价格除以(1+k),卖出价格乘以(1+k) 合并的时候,s0用记录的价格,s1用k修正的 更新目标账号信息 2. 给用户分发dcu 卖出事件 | function sell(uint index, uint amount) external payable override {
require(index != 0, "HF:not exist");
FutureInfo storage fi = _futures[index];
bool orientation = fi.orientation;
uint oraclePrice = _queryPrice(0, fi.tokenAddress, !orientation, msg.sender);
Account memory account = fi.accounts[msg.sender];
account.balance -= _toUInt128(amount);
fi.accounts[msg.sender] = account;
uint value = _balanceOf(
amount,
_decodeFloat(account.basePrice),
uint(account.baseBlock),
oraclePrice,
orientation,
uint(fi.lever)
);
DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, value);
emit Sell(index, amount, msg.sender, value);
}
| 6,664,711 | [
1,
166,
240,
249,
166,
234,
123,
167,
113,
121,
168,
124,
260,
166,
243,
235,
168,
123,
104,
225,
770,
225,
167,
113,
121,
168,
124,
260,
166,
243,
235,
168,
123,
104,
168,
125,
249,
166,
242,
120,
225,
3844,
225,
166,
240,
249,
166,
234,
123,
167,
248,
113,
170,
234,
242,
404,
18,
225,
170,
247,
227,
167,
112,
228,
168,
247,
106,
167,
235,
120,
168,
253,
231,
167,
113,
121,
168,
124,
260,
166,
243,
235,
168,
123,
104,
225,
168,
255,
238,
167,
119,
106,
168,
253,
231,
167,
250,
119,
166,
227,
252,
176,
125,
239,
166,
235,
256,
166,
105,
238,
165,
124,
120,
167,
259,
125,
165,
122,
251,
165,
124,
103,
12,
21,
15,
79,
13,
176,
125,
239,
166,
240,
249,
166,
234,
123,
165,
124,
120,
167,
259,
125,
170,
252,
102,
165,
124,
103,
12,
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,
357,
80,
12,
11890,
770,
16,
2254,
3844,
13,
3903,
8843,
429,
3849,
288,
203,
203,
3639,
2583,
12,
1615,
480,
374,
16,
315,
44,
42,
30,
902,
1005,
8863,
203,
3639,
9108,
966,
2502,
7314,
273,
389,
74,
10945,
63,
1615,
15533,
203,
3639,
1426,
9820,
273,
7314,
18,
19235,
31,
203,
203,
3639,
2254,
20865,
5147,
273,
389,
2271,
5147,
12,
20,
16,
7314,
18,
2316,
1887,
16,
401,
19235,
16,
1234,
18,
15330,
1769,
203,
203,
3639,
6590,
3778,
2236,
273,
7314,
18,
13739,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
2236,
18,
12296,
3947,
389,
869,
14342,
10392,
12,
8949,
1769,
203,
3639,
7314,
18,
13739,
63,
3576,
18,
15330,
65,
273,
2236,
31,
203,
203,
3639,
2254,
460,
273,
389,
12296,
951,
12,
203,
5411,
3844,
16,
7010,
5411,
389,
3922,
4723,
12,
4631,
18,
1969,
5147,
3631,
7010,
5411,
2254,
12,
4631,
18,
1969,
1768,
3631,
203,
5411,
20865,
5147,
16,
7010,
5411,
9820,
16,
7010,
5411,
2254,
12,
22056,
18,
298,
502,
13,
203,
3639,
11272,
203,
3639,
463,
16001,
12,
5528,
57,
67,
8412,
67,
15140,
2934,
81,
474,
12,
3576,
18,
15330,
16,
460,
1769,
203,
203,
3639,
3626,
348,
1165,
12,
1615,
16,
3844,
16,
1234,
18,
15330,
16,
460,
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
] |
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/contracts/interfaces/types/Accumulator.sol | * @notice Sums the maker and taker together from a single accumulator @param self The struct to operate on @return The sum of its maker and taker/ | function sum(Accumulator memory self) internal pure returns (Fixed18) {
return self.maker.add(self.taker);
}
| 1,912,713 | [
1,
3495,
87,
326,
312,
6388,
471,
268,
6388,
9475,
628,
279,
2202,
13514,
225,
365,
1021,
1958,
358,
20829,
603,
327,
1021,
2142,
434,
2097,
312,
6388,
471,
268,
6388,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2142,
12,
27361,
3778,
365,
13,
2713,
16618,
1135,
261,
7505,
2643,
13,
288,
203,
3639,
327,
365,
18,
29261,
18,
1289,
12,
2890,
18,
88,
6388,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.